Bug Summary

File:clang/lib/AST/ASTImporter.cpp
Warning:line 3416, column 53
1st function call argument is an uninitialized value

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ASTImporter.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include -I /build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2021-01-26-035717-31997-1 -x c++ /build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp

/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp

1//===- ASTImporter.cpp - Importing ASTs from other Contexts ---------------===//
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 defines the ASTImporter class which imports AST nodes from one
10// context into another context.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTImporter.h"
15#include "clang/AST/ASTImporterSharedState.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTDiagnostic.h"
18#include "clang/AST/ASTStructuralEquivalence.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclAccessPair.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclFriend.h"
25#include "clang/AST/DeclGroup.h"
26#include "clang/AST/DeclObjC.h"
27#include "clang/AST/DeclTemplate.h"
28#include "clang/AST/DeclVisitor.h"
29#include "clang/AST/DeclarationName.h"
30#include "clang/AST/Expr.h"
31#include "clang/AST/ExprCXX.h"
32#include "clang/AST/ExprObjC.h"
33#include "clang/AST/ExternalASTSource.h"
34#include "clang/AST/LambdaCapture.h"
35#include "clang/AST/NestedNameSpecifier.h"
36#include "clang/AST/OperationKinds.h"
37#include "clang/AST/Stmt.h"
38#include "clang/AST/StmtCXX.h"
39#include "clang/AST/StmtObjC.h"
40#include "clang/AST/StmtVisitor.h"
41#include "clang/AST/TemplateBase.h"
42#include "clang/AST/TemplateName.h"
43#include "clang/AST/Type.h"
44#include "clang/AST/TypeLoc.h"
45#include "clang/AST/TypeVisitor.h"
46#include "clang/AST/UnresolvedSet.h"
47#include "clang/Basic/Builtins.h"
48#include "clang/Basic/ExceptionSpecificationType.h"
49#include "clang/Basic/FileManager.h"
50#include "clang/Basic/IdentifierTable.h"
51#include "clang/Basic/LLVM.h"
52#include "clang/Basic/LangOptions.h"
53#include "clang/Basic/SourceLocation.h"
54#include "clang/Basic/SourceManager.h"
55#include "clang/Basic/Specifiers.h"
56#include "llvm/ADT/APSInt.h"
57#include "llvm/ADT/ArrayRef.h"
58#include "llvm/ADT/DenseMap.h"
59#include "llvm/ADT/None.h"
60#include "llvm/ADT/Optional.h"
61#include "llvm/ADT/ScopeExit.h"
62#include "llvm/ADT/STLExtras.h"
63#include "llvm/ADT/SmallVector.h"
64#include "llvm/Support/Casting.h"
65#include "llvm/Support/ErrorHandling.h"
66#include "llvm/Support/MemoryBuffer.h"
67#include <algorithm>
68#include <cassert>
69#include <cstddef>
70#include <memory>
71#include <type_traits>
72#include <utility>
73
74namespace clang {
75
76 using llvm::make_error;
77 using llvm::Error;
78 using llvm::Expected;
79 using ExpectedType = llvm::Expected<QualType>;
80 using ExpectedStmt = llvm::Expected<Stmt *>;
81 using ExpectedExpr = llvm::Expected<Expr *>;
82 using ExpectedDecl = llvm::Expected<Decl *>;
83 using ExpectedSLoc = llvm::Expected<SourceLocation>;
84 using ExpectedName = llvm::Expected<DeclarationName>;
85
86 std::string ImportError::toString() const {
87 // FIXME: Improve error texts.
88 switch (Error) {
89 case NameConflict:
90 return "NameConflict";
91 case UnsupportedConstruct:
92 return "UnsupportedConstruct";
93 case Unknown:
94 return "Unknown error";
95 }
96 llvm_unreachable("Invalid error code.")::llvm::llvm_unreachable_internal("Invalid error code.", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 96)
;
97 return "Invalid error code.";
98 }
99
100 void ImportError::log(raw_ostream &OS) const {
101 OS << toString();
102 }
103
104 std::error_code ImportError::convertToErrorCode() const {
105 llvm_unreachable("Function not implemented.")::llvm::llvm_unreachable_internal("Function not implemented."
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 105)
;
106 }
107
108 char ImportError::ID;
109
110 template <class T>
111 SmallVector<Decl *, 2>
112 getCanonicalForwardRedeclChain(Redeclarable<T>* D) {
113 SmallVector<Decl *, 2> Redecls;
114 for (auto *R : D->getFirstDecl()->redecls()) {
115 if (R != D->getFirstDecl())
116 Redecls.push_back(R);
117 }
118 Redecls.push_back(D->getFirstDecl());
119 std::reverse(Redecls.begin(), Redecls.end());
120 return Redecls;
121 }
122
123 SmallVector<Decl*, 2> getCanonicalForwardRedeclChain(Decl* D) {
124 if (auto *FD = dyn_cast<FunctionDecl>(D))
125 return getCanonicalForwardRedeclChain<FunctionDecl>(FD);
126 if (auto *VD = dyn_cast<VarDecl>(D))
127 return getCanonicalForwardRedeclChain<VarDecl>(VD);
128 if (auto *TD = dyn_cast<TagDecl>(D))
129 return getCanonicalForwardRedeclChain<TagDecl>(TD);
130 llvm_unreachable("Bad declaration kind")::llvm::llvm_unreachable_internal("Bad declaration kind", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 130)
;
131 }
132
133 void updateFlags(const Decl *From, Decl *To) {
134 // Check if some flags or attrs are new in 'From' and copy into 'To'.
135 // FIXME: Other flags or attrs?
136 if (From->isUsed(false) && !To->isUsed(false))
137 To->setIsUsed();
138 }
139
140 class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, ExpectedType>,
141 public DeclVisitor<ASTNodeImporter, ExpectedDecl>,
142 public StmtVisitor<ASTNodeImporter, ExpectedStmt> {
143 ASTImporter &Importer;
144
145 // Use this instead of Importer.importInto .
146 template <typename ImportT>
147 LLVM_NODISCARD[[clang::warn_unused_result]] Error importInto(ImportT &To, const ImportT &From) {
148 return Importer.importInto(To, From);
149 }
150
151 // Use this to import pointers of specific type.
152 template <typename ImportT>
153 LLVM_NODISCARD[[clang::warn_unused_result]] Error importInto(ImportT *&To, ImportT *From) {
154 auto ToOrErr = Importer.Import(From);
155 if (ToOrErr)
156 To = cast_or_null<ImportT>(*ToOrErr);
157 return ToOrErr.takeError();
158 }
159
160 // Call the import function of ASTImporter for a baseclass of type `T` and
161 // cast the return value to `T`.
162 template <typename T>
163 Expected<T *> import(T *From) {
164 auto ToOrErr = Importer.Import(From);
165 if (!ToOrErr)
166 return ToOrErr.takeError();
167 return cast_or_null<T>(*ToOrErr);
168 }
169
170 template <typename T>
171 Expected<T *> import(const T *From) {
172 return import(const_cast<T *>(From));
173 }
174
175 // Call the import function of ASTImporter for type `T`.
176 template <typename T>
177 Expected<T> import(const T &From) {
178 return Importer.Import(From);
179 }
180
181 // Import an Optional<T> by importing the contained T, if any.
182 template<typename T>
183 Expected<Optional<T>> import(Optional<T> From) {
184 if (!From)
185 return Optional<T>();
186 return import(*From);
187 }
188
189 // Helper for chaining together multiple imports. If an error is detected,
190 // subsequent imports will return default constructed nodes, so that failure
191 // can be detected with a single conditional branch after a sequence of
192 // imports.
193 template <typename T> T importChecked(Error &Err, const T &From) {
194 // Don't attempt to import nodes if we hit an error earlier.
195 if (Err)
196 return T{};
197 Expected<T> MaybeVal = import(From);
198 if (!MaybeVal) {
199 Err = MaybeVal.takeError();
200 return T{};
201 }
202 return *MaybeVal;
203 }
204
205 ExplicitSpecifier importExplicitSpecifier(Error &Err,
206 ExplicitSpecifier ESpec);
207
208 // Wrapper for an overload set.
209 template <typename ToDeclT> struct CallOverloadedCreateFun {
210 template <typename... Args> decltype(auto) operator()(Args &&... args) {
211 return ToDeclT::Create(std::forward<Args>(args)...);
212 }
213 };
214
215 // Always use these functions to create a Decl during import. There are
216 // certain tasks which must be done after the Decl was created, e.g. we
217 // must immediately register that as an imported Decl. The parameter `ToD`
218 // will be set to the newly created Decl or if had been imported before
219 // then to the already imported Decl. Returns a bool value set to true if
220 // the `FromD` had been imported before.
221 template <typename ToDeclT, typename FromDeclT, typename... Args>
222 LLVM_NODISCARD[[clang::warn_unused_result]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
223 Args &&... args) {
224 // There may be several overloads of ToDeclT::Create. We must make sure
225 // to call the one which would be chosen by the arguments, thus we use a
226 // wrapper for the overload set.
227 CallOverloadedCreateFun<ToDeclT> OC;
228 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
229 std::forward<Args>(args)...);
230 }
231 // Use this overload if a special Type is needed to be created. E.g if we
232 // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl`
233 // then:
234 // TypedefNameDecl *ToTypedef;
235 // GetImportedOrCreateDecl<TypeAliasDecl>(ToTypedef, FromD, ...);
236 template <typename NewDeclT, typename ToDeclT, typename FromDeclT,
237 typename... Args>
238 LLVM_NODISCARD[[clang::warn_unused_result]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
239 Args &&... args) {
240 CallOverloadedCreateFun<NewDeclT> OC;
241 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
242 std::forward<Args>(args)...);
243 }
244 // Use this version if a special create function must be
245 // used, e.g. CXXRecordDecl::CreateLambda .
246 template <typename ToDeclT, typename CreateFunT, typename FromDeclT,
247 typename... Args>
248 LLVM_NODISCARD[[clang::warn_unused_result]] bool
249 GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun,
250 FromDeclT *FromD, Args &&... args) {
251 if (Importer.getImportDeclErrorIfAny(FromD)) {
252 ToD = nullptr;
253 return true; // Already imported but with error.
254 }
255 ToD = cast_or_null<ToDeclT>(Importer.GetAlreadyImportedOrNull(FromD));
256 if (ToD)
257 return true; // Already imported.
258 ToD = CreateFun(std::forward<Args>(args)...);
259 // Keep track of imported Decls.
260 Importer.RegisterImportedDecl(FromD, ToD);
261 InitializeImportedDecl(FromD, ToD);
262 return false; // A new Decl is created.
263 }
264
265 void InitializeImportedDecl(Decl *FromD, Decl *ToD) {
266 ToD->IdentifierNamespace = FromD->IdentifierNamespace;
267 if (FromD->isUsed())
268 ToD->setIsUsed();
269 if (FromD->isImplicit())
270 ToD->setImplicit();
271 }
272
273 // Check if we have found an existing definition. Returns with that
274 // definition if yes, otherwise returns null.
275 Decl *FindAndMapDefinition(FunctionDecl *D, FunctionDecl *FoundFunction) {
276 const FunctionDecl *Definition = nullptr;
277 if (D->doesThisDeclarationHaveABody() &&
278 FoundFunction->hasBody(Definition))
279 return Importer.MapImported(D, const_cast<FunctionDecl *>(Definition));
280 return nullptr;
281 }
282
283 void addDeclToContexts(Decl *FromD, Decl *ToD) {
284 if (Importer.isMinimalImport()) {
285 // In minimal import case the decl must be added even if it is not
286 // contained in original context, for LLDB compatibility.
287 // FIXME: Check if a better solution is possible.
288 if (!FromD->getDescribedTemplate() &&
289 FromD->getFriendObjectKind() == Decl::FOK_None)
290 ToD->getLexicalDeclContext()->addDeclInternal(ToD);
291 return;
292 }
293
294 DeclContext *FromDC = FromD->getDeclContext();
295 DeclContext *FromLexicalDC = FromD->getLexicalDeclContext();
296 DeclContext *ToDC = ToD->getDeclContext();
297 DeclContext *ToLexicalDC = ToD->getLexicalDeclContext();
298
299 bool Visible = false;
300 if (FromDC->containsDeclAndLoad(FromD)) {
301 ToDC->addDeclInternal(ToD);
302 Visible = true;
303 }
304 if (ToDC != ToLexicalDC && FromLexicalDC->containsDeclAndLoad(FromD)) {
305 ToLexicalDC->addDeclInternal(ToD);
306 Visible = true;
307 }
308
309 // If the Decl was added to any context, it was made already visible.
310 // Otherwise it is still possible that it should be visible.
311 if (!Visible) {
312 if (auto *FromNamed = dyn_cast<NamedDecl>(FromD)) {
313 auto *ToNamed = cast<NamedDecl>(ToD);
314 DeclContextLookupResult FromLookup =
315 FromDC->lookup(FromNamed->getDeclName());
316 for (NamedDecl *ND : FromLookup)
317 if (ND == FromNamed) {
318 ToDC->makeDeclVisibleInContext(ToNamed);
319 break;
320 }
321 }
322 }
323 }
324
325 public:
326 explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {}
327
328 using TypeVisitor<ASTNodeImporter, ExpectedType>::Visit;
329 using DeclVisitor<ASTNodeImporter, ExpectedDecl>::Visit;
330 using StmtVisitor<ASTNodeImporter, ExpectedStmt>::Visit;
331
332 // Importing types
333 ExpectedType VisitType(const Type *T);
334 ExpectedType VisitAtomicType(const AtomicType *T);
335 ExpectedType VisitBuiltinType(const BuiltinType *T);
336 ExpectedType VisitDecayedType(const DecayedType *T);
337 ExpectedType VisitComplexType(const ComplexType *T);
338 ExpectedType VisitPointerType(const PointerType *T);
339 ExpectedType VisitBlockPointerType(const BlockPointerType *T);
340 ExpectedType VisitLValueReferenceType(const LValueReferenceType *T);
341 ExpectedType VisitRValueReferenceType(const RValueReferenceType *T);
342 ExpectedType VisitMemberPointerType(const MemberPointerType *T);
343 ExpectedType VisitConstantArrayType(const ConstantArrayType *T);
344 ExpectedType VisitIncompleteArrayType(const IncompleteArrayType *T);
345 ExpectedType VisitVariableArrayType(const VariableArrayType *T);
346 ExpectedType VisitDependentSizedArrayType(const DependentSizedArrayType *T);
347 // FIXME: DependentSizedExtVectorType
348 ExpectedType VisitVectorType(const VectorType *T);
349 ExpectedType VisitExtVectorType(const ExtVectorType *T);
350 ExpectedType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
351 ExpectedType VisitFunctionProtoType(const FunctionProtoType *T);
352 ExpectedType VisitUnresolvedUsingType(const UnresolvedUsingType *T);
353 ExpectedType VisitParenType(const ParenType *T);
354 ExpectedType VisitTypedefType(const TypedefType *T);
355 ExpectedType VisitTypeOfExprType(const TypeOfExprType *T);
356 // FIXME: DependentTypeOfExprType
357 ExpectedType VisitTypeOfType(const TypeOfType *T);
358 ExpectedType VisitDecltypeType(const DecltypeType *T);
359 ExpectedType VisitUnaryTransformType(const UnaryTransformType *T);
360 ExpectedType VisitAutoType(const AutoType *T);
361 ExpectedType VisitInjectedClassNameType(const InjectedClassNameType *T);
362 // FIXME: DependentDecltypeType
363 ExpectedType VisitRecordType(const RecordType *T);
364 ExpectedType VisitEnumType(const EnumType *T);
365 ExpectedType VisitAttributedType(const AttributedType *T);
366 ExpectedType VisitTemplateTypeParmType(const TemplateTypeParmType *T);
367 ExpectedType VisitSubstTemplateTypeParmType(
368 const SubstTemplateTypeParmType *T);
369 ExpectedType VisitTemplateSpecializationType(
370 const TemplateSpecializationType *T);
371 ExpectedType VisitElaboratedType(const ElaboratedType *T);
372 ExpectedType VisitDependentNameType(const DependentNameType *T);
373 ExpectedType VisitPackExpansionType(const PackExpansionType *T);
374 ExpectedType VisitDependentTemplateSpecializationType(
375 const DependentTemplateSpecializationType *T);
376 ExpectedType VisitObjCInterfaceType(const ObjCInterfaceType *T);
377 ExpectedType VisitObjCObjectType(const ObjCObjectType *T);
378 ExpectedType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
379
380 // Importing declarations
381 Error ImportDeclParts(NamedDecl *D, DeclarationName &Name, NamedDecl *&ToD,
382 SourceLocation &Loc);
383 Error ImportDeclParts(
384 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
385 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc);
386 Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
387 Error ImportDeclarationNameLoc(
388 const DeclarationNameInfo &From, DeclarationNameInfo &To);
389 Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
390 Error ImportDeclContext(
391 Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC);
392 Error ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To);
393
394 Expected<CXXCastPath> ImportCastPath(CastExpr *E);
395 Expected<APValue> ImportAPValue(const APValue &FromValue);
396
397 using Designator = DesignatedInitExpr::Designator;
398
399 /// What we should import from the definition.
400 enum ImportDefinitionKind {
401 /// Import the default subset of the definition, which might be
402 /// nothing (if minimal import is set) or might be everything (if minimal
403 /// import is not set).
404 IDK_Default,
405 /// Import everything.
406 IDK_Everything,
407 /// Import only the bare bones needed to establish a valid
408 /// DeclContext.
409 IDK_Basic
410 };
411
412 bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
413 return IDK == IDK_Everything ||
414 (IDK == IDK_Default && !Importer.isMinimalImport());
415 }
416
417 Error ImportInitializer(VarDecl *From, VarDecl *To);
418 Error ImportDefinition(
419 RecordDecl *From, RecordDecl *To,
420 ImportDefinitionKind Kind = IDK_Default);
421 Error ImportDefinition(
422 EnumDecl *From, EnumDecl *To,
423 ImportDefinitionKind Kind = IDK_Default);
424 Error ImportDefinition(
425 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
426 ImportDefinitionKind Kind = IDK_Default);
427 Error ImportDefinition(
428 ObjCProtocolDecl *From, ObjCProtocolDecl *To,
429 ImportDefinitionKind Kind = IDK_Default);
430 Error ImportTemplateArguments(
431 const TemplateArgument *FromArgs, unsigned NumFromArgs,
432 SmallVectorImpl<TemplateArgument> &ToArgs);
433 Expected<TemplateArgument>
434 ImportTemplateArgument(const TemplateArgument &From);
435
436 template <typename InContainerTy>
437 Error ImportTemplateArgumentListInfo(
438 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo);
439
440 template<typename InContainerTy>
441 Error ImportTemplateArgumentListInfo(
442 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
443 const InContainerTy &Container, TemplateArgumentListInfo &Result);
444
445 using TemplateArgsTy = SmallVector<TemplateArgument, 8>;
446 using FunctionTemplateAndArgsTy =
447 std::tuple<FunctionTemplateDecl *, TemplateArgsTy>;
448 Expected<FunctionTemplateAndArgsTy>
449 ImportFunctionTemplateWithTemplateArgsFromSpecialization(
450 FunctionDecl *FromFD);
451 Error ImportTemplateParameterLists(const DeclaratorDecl *FromD,
452 DeclaratorDecl *ToD);
453
454 Error ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD);
455
456 Error ImportFunctionDeclBody(FunctionDecl *FromFD, FunctionDecl *ToFD);
457
458 Error ImportDefaultArgOfParmVarDecl(const ParmVarDecl *FromParam,
459 ParmVarDecl *ToParam);
460
461 template <typename T>
462 bool hasSameVisibilityContextAndLinkage(T *Found, T *From);
463
464 bool IsStructuralMatch(Decl *From, Decl *To, bool Complain);
465 bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
466 bool Complain = true);
467 bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
468 bool Complain = true);
469 bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
470 bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
471 bool IsStructuralMatch(FunctionTemplateDecl *From,
472 FunctionTemplateDecl *To);
473 bool IsStructuralMatch(FunctionDecl *From, FunctionDecl *To);
474 bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
475 bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
476 ExpectedDecl VisitDecl(Decl *D);
477 ExpectedDecl VisitImportDecl(ImportDecl *D);
478 ExpectedDecl VisitEmptyDecl(EmptyDecl *D);
479 ExpectedDecl VisitAccessSpecDecl(AccessSpecDecl *D);
480 ExpectedDecl VisitStaticAssertDecl(StaticAssertDecl *D);
481 ExpectedDecl VisitTranslationUnitDecl(TranslationUnitDecl *D);
482 ExpectedDecl VisitNamespaceDecl(NamespaceDecl *D);
483 ExpectedDecl VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
484 ExpectedDecl VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
485 ExpectedDecl VisitTypedefDecl(TypedefDecl *D);
486 ExpectedDecl VisitTypeAliasDecl(TypeAliasDecl *D);
487 ExpectedDecl VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
488 ExpectedDecl VisitLabelDecl(LabelDecl *D);
489 ExpectedDecl VisitEnumDecl(EnumDecl *D);
490 ExpectedDecl VisitRecordDecl(RecordDecl *D);
491 ExpectedDecl VisitEnumConstantDecl(EnumConstantDecl *D);
492 ExpectedDecl VisitFunctionDecl(FunctionDecl *D);
493 ExpectedDecl VisitCXXMethodDecl(CXXMethodDecl *D);
494 ExpectedDecl VisitCXXConstructorDecl(CXXConstructorDecl *D);
495 ExpectedDecl VisitCXXDestructorDecl(CXXDestructorDecl *D);
496 ExpectedDecl VisitCXXConversionDecl(CXXConversionDecl *D);
497 ExpectedDecl VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D);
498 ExpectedDecl VisitFieldDecl(FieldDecl *D);
499 ExpectedDecl VisitIndirectFieldDecl(IndirectFieldDecl *D);
500 ExpectedDecl VisitFriendDecl(FriendDecl *D);
501 ExpectedDecl VisitObjCIvarDecl(ObjCIvarDecl *D);
502 ExpectedDecl VisitVarDecl(VarDecl *D);
503 ExpectedDecl VisitImplicitParamDecl(ImplicitParamDecl *D);
504 ExpectedDecl VisitParmVarDecl(ParmVarDecl *D);
505 ExpectedDecl VisitObjCMethodDecl(ObjCMethodDecl *D);
506 ExpectedDecl VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
507 ExpectedDecl VisitObjCCategoryDecl(ObjCCategoryDecl *D);
508 ExpectedDecl VisitObjCProtocolDecl(ObjCProtocolDecl *D);
509 ExpectedDecl VisitLinkageSpecDecl(LinkageSpecDecl *D);
510 ExpectedDecl VisitUsingDecl(UsingDecl *D);
511 ExpectedDecl VisitUsingShadowDecl(UsingShadowDecl *D);
512 ExpectedDecl VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
513 ExpectedDecl VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
514 ExpectedDecl VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
515 ExpectedDecl VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);
516 ExpectedDecl
517 VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D);
518
519 Expected<ObjCTypeParamList *>
520 ImportObjCTypeParamList(ObjCTypeParamList *list);
521
522 ExpectedDecl VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
523 ExpectedDecl VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
524 ExpectedDecl VisitObjCImplementationDecl(ObjCImplementationDecl *D);
525 ExpectedDecl VisitObjCPropertyDecl(ObjCPropertyDecl *D);
526 ExpectedDecl VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
527 ExpectedDecl VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
528 ExpectedDecl VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
529 ExpectedDecl VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
530 ExpectedDecl VisitClassTemplateDecl(ClassTemplateDecl *D);
531 ExpectedDecl VisitClassTemplateSpecializationDecl(
532 ClassTemplateSpecializationDecl *D);
533 ExpectedDecl VisitVarTemplateDecl(VarTemplateDecl *D);
534 ExpectedDecl VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
535 ExpectedDecl VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
536
537 // Importing statements
538 ExpectedStmt VisitStmt(Stmt *S);
539 ExpectedStmt VisitGCCAsmStmt(GCCAsmStmt *S);
540 ExpectedStmt VisitDeclStmt(DeclStmt *S);
541 ExpectedStmt VisitNullStmt(NullStmt *S);
542 ExpectedStmt VisitCompoundStmt(CompoundStmt *S);
543 ExpectedStmt VisitCaseStmt(CaseStmt *S);
544 ExpectedStmt VisitDefaultStmt(DefaultStmt *S);
545 ExpectedStmt VisitLabelStmt(LabelStmt *S);
546 ExpectedStmt VisitAttributedStmt(AttributedStmt *S);
547 ExpectedStmt VisitIfStmt(IfStmt *S);
548 ExpectedStmt VisitSwitchStmt(SwitchStmt *S);
549 ExpectedStmt VisitWhileStmt(WhileStmt *S);
550 ExpectedStmt VisitDoStmt(DoStmt *S);
551 ExpectedStmt VisitForStmt(ForStmt *S);
552 ExpectedStmt VisitGotoStmt(GotoStmt *S);
553 ExpectedStmt VisitIndirectGotoStmt(IndirectGotoStmt *S);
554 ExpectedStmt VisitContinueStmt(ContinueStmt *S);
555 ExpectedStmt VisitBreakStmt(BreakStmt *S);
556 ExpectedStmt VisitReturnStmt(ReturnStmt *S);
557 // FIXME: MSAsmStmt
558 // FIXME: SEHExceptStmt
559 // FIXME: SEHFinallyStmt
560 // FIXME: SEHTryStmt
561 // FIXME: SEHLeaveStmt
562 // FIXME: CapturedStmt
563 ExpectedStmt VisitCXXCatchStmt(CXXCatchStmt *S);
564 ExpectedStmt VisitCXXTryStmt(CXXTryStmt *S);
565 ExpectedStmt VisitCXXForRangeStmt(CXXForRangeStmt *S);
566 // FIXME: MSDependentExistsStmt
567 ExpectedStmt VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
568 ExpectedStmt VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
569 ExpectedStmt VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
570 ExpectedStmt VisitObjCAtTryStmt(ObjCAtTryStmt *S);
571 ExpectedStmt VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
572 ExpectedStmt VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
573 ExpectedStmt VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
574
575 // Importing expressions
576 ExpectedStmt VisitExpr(Expr *E);
577 ExpectedStmt VisitVAArgExpr(VAArgExpr *E);
578 ExpectedStmt VisitChooseExpr(ChooseExpr *E);
579 ExpectedStmt VisitGNUNullExpr(GNUNullExpr *E);
580 ExpectedStmt VisitGenericSelectionExpr(GenericSelectionExpr *E);
581 ExpectedStmt VisitPredefinedExpr(PredefinedExpr *E);
582 ExpectedStmt VisitDeclRefExpr(DeclRefExpr *E);
583 ExpectedStmt VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
584 ExpectedStmt VisitDesignatedInitExpr(DesignatedInitExpr *E);
585 ExpectedStmt VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E);
586 ExpectedStmt VisitIntegerLiteral(IntegerLiteral *E);
587 ExpectedStmt VisitFloatingLiteral(FloatingLiteral *E);
588 ExpectedStmt VisitImaginaryLiteral(ImaginaryLiteral *E);
589 ExpectedStmt VisitFixedPointLiteral(FixedPointLiteral *E);
590 ExpectedStmt VisitCharacterLiteral(CharacterLiteral *E);
591 ExpectedStmt VisitStringLiteral(StringLiteral *E);
592 ExpectedStmt VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
593 ExpectedStmt VisitAtomicExpr(AtomicExpr *E);
594 ExpectedStmt VisitAddrLabelExpr(AddrLabelExpr *E);
595 ExpectedStmt VisitConstantExpr(ConstantExpr *E);
596 ExpectedStmt VisitParenExpr(ParenExpr *E);
597 ExpectedStmt VisitParenListExpr(ParenListExpr *E);
598 ExpectedStmt VisitStmtExpr(StmtExpr *E);
599 ExpectedStmt VisitUnaryOperator(UnaryOperator *E);
600 ExpectedStmt VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
601 ExpectedStmt VisitBinaryOperator(BinaryOperator *E);
602 ExpectedStmt VisitConditionalOperator(ConditionalOperator *E);
603 ExpectedStmt VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
604 ExpectedStmt VisitOpaqueValueExpr(OpaqueValueExpr *E);
605 ExpectedStmt VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
606 ExpectedStmt VisitExpressionTraitExpr(ExpressionTraitExpr *E);
607 ExpectedStmt VisitArraySubscriptExpr(ArraySubscriptExpr *E);
608 ExpectedStmt VisitCompoundAssignOperator(CompoundAssignOperator *E);
609 ExpectedStmt VisitImplicitCastExpr(ImplicitCastExpr *E);
610 ExpectedStmt VisitExplicitCastExpr(ExplicitCastExpr *E);
611 ExpectedStmt VisitOffsetOfExpr(OffsetOfExpr *OE);
612 ExpectedStmt VisitCXXThrowExpr(CXXThrowExpr *E);
613 ExpectedStmt VisitCXXNoexceptExpr(CXXNoexceptExpr *E);
614 ExpectedStmt VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E);
615 ExpectedStmt VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
616 ExpectedStmt VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
617 ExpectedStmt VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
618 ExpectedStmt VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
619 ExpectedStmt VisitPackExpansionExpr(PackExpansionExpr *E);
620 ExpectedStmt VisitSizeOfPackExpr(SizeOfPackExpr *E);
621 ExpectedStmt VisitCXXNewExpr(CXXNewExpr *E);
622 ExpectedStmt VisitCXXDeleteExpr(CXXDeleteExpr *E);
623 ExpectedStmt VisitCXXConstructExpr(CXXConstructExpr *E);
624 ExpectedStmt VisitCXXMemberCallExpr(CXXMemberCallExpr *E);
625 ExpectedStmt VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
626 ExpectedStmt VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
627 ExpectedStmt VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
628 ExpectedStmt VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E);
629 ExpectedStmt VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
630 ExpectedStmt VisitExprWithCleanups(ExprWithCleanups *E);
631 ExpectedStmt VisitCXXThisExpr(CXXThisExpr *E);
632 ExpectedStmt VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E);
633 ExpectedStmt VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
634 ExpectedStmt VisitMemberExpr(MemberExpr *E);
635 ExpectedStmt VisitCallExpr(CallExpr *E);
636 ExpectedStmt VisitLambdaExpr(LambdaExpr *LE);
637 ExpectedStmt VisitInitListExpr(InitListExpr *E);
638 ExpectedStmt VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
639 ExpectedStmt VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E);
640 ExpectedStmt VisitArrayInitLoopExpr(ArrayInitLoopExpr *E);
641 ExpectedStmt VisitArrayInitIndexExpr(ArrayInitIndexExpr *E);
642 ExpectedStmt VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E);
643 ExpectedStmt VisitCXXNamedCastExpr(CXXNamedCastExpr *E);
644 ExpectedStmt VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E);
645 ExpectedStmt VisitTypeTraitExpr(TypeTraitExpr *E);
646 ExpectedStmt VisitCXXTypeidExpr(CXXTypeidExpr *E);
647 ExpectedStmt VisitCXXFoldExpr(CXXFoldExpr *E);
648
649 template<typename IIter, typename OIter>
650 Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
651 using ItemT = std::remove_reference_t<decltype(*Obegin)>;
652 for (; Ibegin != Iend; ++Ibegin, ++Obegin) {
653 Expected<ItemT> ToOrErr = import(*Ibegin);
654 if (!ToOrErr)
655 return ToOrErr.takeError();
656 *Obegin = *ToOrErr;
657 }
658 return Error::success();
659 }
660
661 // Import every item from a container structure into an output container.
662 // If error occurs, stops at first error and returns the error.
663 // The output container should have space for all needed elements (it is not
664 // expanded, new items are put into from the beginning).
665 template<typename InContainerTy, typename OutContainerTy>
666 Error ImportContainerChecked(
667 const InContainerTy &InContainer, OutContainerTy &OutContainer) {
668 return ImportArrayChecked(
669 InContainer.begin(), InContainer.end(), OutContainer.begin());
670 }
671
672 template<typename InContainerTy, typename OIter>
673 Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
674 return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
675 }
676
677 Error ImportOverriddenMethods(CXXMethodDecl *ToMethod,
678 CXXMethodDecl *FromMethod);
679
680 Expected<FunctionDecl *> FindFunctionTemplateSpecialization(
681 FunctionDecl *FromFD);
682
683 // Returns true if the given function has a placeholder return type and
684 // that type is declared inside the body of the function.
685 // E.g. auto f() { struct X{}; return X(); }
686 bool hasAutoReturnTypeDeclaredInside(FunctionDecl *D);
687 };
688
689template <typename InContainerTy>
690Error ASTNodeImporter::ImportTemplateArgumentListInfo(
691 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
692 const InContainerTy &Container, TemplateArgumentListInfo &Result) {
693 auto ToLAngleLocOrErr = import(FromLAngleLoc);
694 if (!ToLAngleLocOrErr)
695 return ToLAngleLocOrErr.takeError();
696 auto ToRAngleLocOrErr = import(FromRAngleLoc);
697 if (!ToRAngleLocOrErr)
698 return ToRAngleLocOrErr.takeError();
699
700 TemplateArgumentListInfo ToTAInfo(*ToLAngleLocOrErr, *ToRAngleLocOrErr);
701 if (auto Err = ImportTemplateArgumentListInfo(Container, ToTAInfo))
702 return Err;
703 Result = ToTAInfo;
704 return Error::success();
705}
706
707template <>
708Error ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>(
709 const TemplateArgumentListInfo &From, TemplateArgumentListInfo &Result) {
710 return ImportTemplateArgumentListInfo(
711 From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result);
712}
713
714template <>
715Error ASTNodeImporter::ImportTemplateArgumentListInfo<
716 ASTTemplateArgumentListInfo>(
717 const ASTTemplateArgumentListInfo &From,
718 TemplateArgumentListInfo &Result) {
719 return ImportTemplateArgumentListInfo(
720 From.LAngleLoc, From.RAngleLoc, From.arguments(), Result);
721}
722
723Expected<ASTNodeImporter::FunctionTemplateAndArgsTy>
724ASTNodeImporter::ImportFunctionTemplateWithTemplateArgsFromSpecialization(
725 FunctionDecl *FromFD) {
726 assert(FromFD->getTemplatedKind() ==((FromFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization
) ? static_cast<void> (0) : __assert_fail ("FromFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 727, __PRETTY_FUNCTION__))
727 FunctionDecl::TK_FunctionTemplateSpecialization)((FromFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization
) ? static_cast<void> (0) : __assert_fail ("FromFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 727, __PRETTY_FUNCTION__))
;
728
729 FunctionTemplateAndArgsTy Result;
730
731 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
732 if (Error Err = importInto(std::get<0>(Result), FTSInfo->getTemplate()))
733 return std::move(Err);
734
735 // Import template arguments.
736 auto TemplArgs = FTSInfo->TemplateArguments->asArray();
737 if (Error Err = ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(),
738 std::get<1>(Result)))
739 return std::move(Err);
740
741 return Result;
742}
743
744template <>
745Expected<TemplateParameterList *>
746ASTNodeImporter::import(TemplateParameterList *From) {
747 SmallVector<NamedDecl *, 4> To(From->size());
748 if (Error Err = ImportContainerChecked(*From, To))
749 return std::move(Err);
750
751 ExpectedExpr ToRequiresClause = import(From->getRequiresClause());
752 if (!ToRequiresClause)
753 return ToRequiresClause.takeError();
754
755 auto ToTemplateLocOrErr = import(From->getTemplateLoc());
756 if (!ToTemplateLocOrErr)
757 return ToTemplateLocOrErr.takeError();
758 auto ToLAngleLocOrErr = import(From->getLAngleLoc());
759 if (!ToLAngleLocOrErr)
760 return ToLAngleLocOrErr.takeError();
761 auto ToRAngleLocOrErr = import(From->getRAngleLoc());
762 if (!ToRAngleLocOrErr)
763 return ToRAngleLocOrErr.takeError();
764
765 return TemplateParameterList::Create(
766 Importer.getToContext(),
767 *ToTemplateLocOrErr,
768 *ToLAngleLocOrErr,
769 To,
770 *ToRAngleLocOrErr,
771 *ToRequiresClause);
772}
773
774template <>
775Expected<TemplateArgument>
776ASTNodeImporter::import(const TemplateArgument &From) {
777 switch (From.getKind()) {
778 case TemplateArgument::Null:
779 return TemplateArgument();
780
781 case TemplateArgument::Type: {
782 ExpectedType ToTypeOrErr = import(From.getAsType());
783 if (!ToTypeOrErr)
784 return ToTypeOrErr.takeError();
785 return TemplateArgument(*ToTypeOrErr);
786 }
787
788 case TemplateArgument::Integral: {
789 ExpectedType ToTypeOrErr = import(From.getIntegralType());
790 if (!ToTypeOrErr)
791 return ToTypeOrErr.takeError();
792 return TemplateArgument(From, *ToTypeOrErr);
793 }
794
795 case TemplateArgument::Declaration: {
796 Expected<ValueDecl *> ToOrErr = import(From.getAsDecl());
797 if (!ToOrErr)
798 return ToOrErr.takeError();
799 ExpectedType ToTypeOrErr = import(From.getParamTypeForDecl());
800 if (!ToTypeOrErr)
801 return ToTypeOrErr.takeError();
802 return TemplateArgument(*ToOrErr, *ToTypeOrErr);
803 }
804
805 case TemplateArgument::NullPtr: {
806 ExpectedType ToTypeOrErr = import(From.getNullPtrType());
807 if (!ToTypeOrErr)
808 return ToTypeOrErr.takeError();
809 return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/true);
810 }
811
812 case TemplateArgument::Template: {
813 Expected<TemplateName> ToTemplateOrErr = import(From.getAsTemplate());
814 if (!ToTemplateOrErr)
815 return ToTemplateOrErr.takeError();
816
817 return TemplateArgument(*ToTemplateOrErr);
818 }
819
820 case TemplateArgument::TemplateExpansion: {
821 Expected<TemplateName> ToTemplateOrErr =
822 import(From.getAsTemplateOrTemplatePattern());
823 if (!ToTemplateOrErr)
824 return ToTemplateOrErr.takeError();
825
826 return TemplateArgument(
827 *ToTemplateOrErr, From.getNumTemplateExpansions());
828 }
829
830 case TemplateArgument::Expression:
831 if (ExpectedExpr ToExpr = import(From.getAsExpr()))
832 return TemplateArgument(*ToExpr);
833 else
834 return ToExpr.takeError();
835
836 case TemplateArgument::Pack: {
837 SmallVector<TemplateArgument, 2> ToPack;
838 ToPack.reserve(From.pack_size());
839 if (Error Err = ImportTemplateArguments(
840 From.pack_begin(), From.pack_size(), ToPack))
841 return std::move(Err);
842
843 return TemplateArgument(
844 llvm::makeArrayRef(ToPack).copy(Importer.getToContext()));
845 }
846 }
847
848 llvm_unreachable("Invalid template argument kind")::llvm::llvm_unreachable_internal("Invalid template argument kind"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 848)
;
849}
850
851template <>
852Expected<TemplateArgumentLoc>
853ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) {
854 Expected<TemplateArgument> ArgOrErr = import(TALoc.getArgument());
855 if (!ArgOrErr)
856 return ArgOrErr.takeError();
857 TemplateArgument Arg = *ArgOrErr;
858
859 TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
860
861 TemplateArgumentLocInfo ToInfo;
862 if (Arg.getKind() == TemplateArgument::Expression) {
863 ExpectedExpr E = import(FromInfo.getAsExpr());
864 if (!E)
865 return E.takeError();
866 ToInfo = TemplateArgumentLocInfo(*E);
867 } else if (Arg.getKind() == TemplateArgument::Type) {
868 if (auto TSIOrErr = import(FromInfo.getAsTypeSourceInfo()))
869 ToInfo = TemplateArgumentLocInfo(*TSIOrErr);
870 else
871 return TSIOrErr.takeError();
872 } else {
873 auto ToTemplateQualifierLocOrErr =
874 import(FromInfo.getTemplateQualifierLoc());
875 if (!ToTemplateQualifierLocOrErr)
876 return ToTemplateQualifierLocOrErr.takeError();
877 auto ToTemplateNameLocOrErr = import(FromInfo.getTemplateNameLoc());
878 if (!ToTemplateNameLocOrErr)
879 return ToTemplateNameLocOrErr.takeError();
880 auto ToTemplateEllipsisLocOrErr =
881 import(FromInfo.getTemplateEllipsisLoc());
882 if (!ToTemplateEllipsisLocOrErr)
883 return ToTemplateEllipsisLocOrErr.takeError();
884 ToInfo = TemplateArgumentLocInfo(
885 Importer.getToContext(), *ToTemplateQualifierLocOrErr,
886 *ToTemplateNameLocOrErr, *ToTemplateEllipsisLocOrErr);
887 }
888
889 return TemplateArgumentLoc(Arg, ToInfo);
890}
891
892template <>
893Expected<DeclGroupRef> ASTNodeImporter::import(const DeclGroupRef &DG) {
894 if (DG.isNull())
895 return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
896 size_t NumDecls = DG.end() - DG.begin();
897 SmallVector<Decl *, 1> ToDecls;
898 ToDecls.reserve(NumDecls);
899 for (Decl *FromD : DG) {
900 if (auto ToDOrErr = import(FromD))
901 ToDecls.push_back(*ToDOrErr);
902 else
903 return ToDOrErr.takeError();
904 }
905 return DeclGroupRef::Create(Importer.getToContext(),
906 ToDecls.begin(),
907 NumDecls);
908}
909
910template <>
911Expected<ASTNodeImporter::Designator>
912ASTNodeImporter::import(const Designator &D) {
913 if (D.isFieldDesignator()) {
914 IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
915
916 ExpectedSLoc ToDotLocOrErr = import(D.getDotLoc());
917 if (!ToDotLocOrErr)
918 return ToDotLocOrErr.takeError();
919
920 ExpectedSLoc ToFieldLocOrErr = import(D.getFieldLoc());
921 if (!ToFieldLocOrErr)
922 return ToFieldLocOrErr.takeError();
923
924 return Designator(ToFieldName, *ToDotLocOrErr, *ToFieldLocOrErr);
925 }
926
927 ExpectedSLoc ToLBracketLocOrErr = import(D.getLBracketLoc());
928 if (!ToLBracketLocOrErr)
929 return ToLBracketLocOrErr.takeError();
930
931 ExpectedSLoc ToRBracketLocOrErr = import(D.getRBracketLoc());
932 if (!ToRBracketLocOrErr)
933 return ToRBracketLocOrErr.takeError();
934
935 if (D.isArrayDesignator())
936 return Designator(D.getFirstExprIndex(),
937 *ToLBracketLocOrErr, *ToRBracketLocOrErr);
938
939 ExpectedSLoc ToEllipsisLocOrErr = import(D.getEllipsisLoc());
940 if (!ToEllipsisLocOrErr)
941 return ToEllipsisLocOrErr.takeError();
942
943 assert(D.isArrayRangeDesignator())((D.isArrayRangeDesignator()) ? static_cast<void> (0) :
__assert_fail ("D.isArrayRangeDesignator()", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 943, __PRETTY_FUNCTION__))
;
944 return Designator(
945 D.getFirstExprIndex(), *ToLBracketLocOrErr, *ToEllipsisLocOrErr,
946 *ToRBracketLocOrErr);
947}
948
949template <>
950Expected<LambdaCapture> ASTNodeImporter::import(const LambdaCapture &From) {
951 VarDecl *Var = nullptr;
952 if (From.capturesVariable()) {
953 if (auto VarOrErr = import(From.getCapturedVar()))
954 Var = *VarOrErr;
955 else
956 return VarOrErr.takeError();
957 }
958
959 auto LocationOrErr = import(From.getLocation());
960 if (!LocationOrErr)
961 return LocationOrErr.takeError();
962
963 SourceLocation EllipsisLoc;
964 if (From.isPackExpansion())
965 if (Error Err = importInto(EllipsisLoc, From.getEllipsisLoc()))
966 return std::move(Err);
967
968 return LambdaCapture(
969 *LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var,
970 EllipsisLoc);
971}
972
973template <typename T>
974bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(T *Found, T *From) {
975 if (Found->getLinkageInternal() != From->getLinkageInternal())
976 return false;
977
978 if (From->hasExternalFormalLinkage())
979 return Found->hasExternalFormalLinkage();
980 if (Importer.GetFromTU(Found) != From->getTranslationUnitDecl())
981 return false;
982 if (From->isInAnonymousNamespace())
983 return Found->isInAnonymousNamespace();
984 else
985 return !Found->isInAnonymousNamespace() &&
986 !Found->hasExternalFormalLinkage();
987}
988
989template <>
990bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(TypedefNameDecl *Found,
991 TypedefNameDecl *From) {
992 if (Found->getLinkageInternal() != From->getLinkageInternal())
993 return false;
994
995 if (From->isInAnonymousNamespace() && Found->isInAnonymousNamespace())
996 return Importer.GetFromTU(Found) == From->getTranslationUnitDecl();
997 return From->isInAnonymousNamespace() == Found->isInAnonymousNamespace();
998}
999
1000} // namespace clang
1001
1002//----------------------------------------------------------------------------
1003// Import Types
1004//----------------------------------------------------------------------------
1005
1006using namespace clang;
1007
1008ExpectedType ASTNodeImporter::VisitType(const Type *T) {
1009 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1010 << T->getTypeClassName();
1011 return make_error<ImportError>(ImportError::UnsupportedConstruct);
1012}
1013
1014ExpectedType ASTNodeImporter::VisitAtomicType(const AtomicType *T){
1015 ExpectedType UnderlyingTypeOrErr = import(T->getValueType());
1016 if (!UnderlyingTypeOrErr)
1017 return UnderlyingTypeOrErr.takeError();
1018
1019 return Importer.getToContext().getAtomicType(*UnderlyingTypeOrErr);
1020}
1021
1022ExpectedType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
1023 switch (T->getKind()) {
1024#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1025 case BuiltinType::Id: \
1026 return Importer.getToContext().SingletonId;
1027#include "clang/Basic/OpenCLImageTypes.def"
1028#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1029 case BuiltinType::Id: \
1030 return Importer.getToContext().Id##Ty;
1031#include "clang/Basic/OpenCLExtensionTypes.def"
1032#define SVE_TYPE(Name, Id, SingletonId) \
1033 case BuiltinType::Id: \
1034 return Importer.getToContext().SingletonId;
1035#include "clang/Basic/AArch64SVEACLETypes.def"
1036#define PPC_VECTOR_TYPE(Name, Id, Size) \
1037 case BuiltinType::Id: \
1038 return Importer.getToContext().Id##Ty;
1039#include "clang/Basic/PPCTypes.def"
1040#define SHARED_SINGLETON_TYPE(Expansion)
1041#define BUILTIN_TYPE(Id, SingletonId) \
1042 case BuiltinType::Id: return Importer.getToContext().SingletonId;
1043#include "clang/AST/BuiltinTypes.def"
1044
1045 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1046 // context supports C++.
1047
1048 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1049 // context supports ObjC.
1050
1051 case BuiltinType::Char_U:
1052 // The context we're importing from has an unsigned 'char'. If we're
1053 // importing into a context with a signed 'char', translate to
1054 // 'unsigned char' instead.
1055 if (Importer.getToContext().getLangOpts().CharIsSigned)
1056 return Importer.getToContext().UnsignedCharTy;
1057
1058 return Importer.getToContext().CharTy;
1059
1060 case BuiltinType::Char_S:
1061 // The context we're importing from has an unsigned 'char'. If we're
1062 // importing into a context with a signed 'char', translate to
1063 // 'unsigned char' instead.
1064 if (!Importer.getToContext().getLangOpts().CharIsSigned)
1065 return Importer.getToContext().SignedCharTy;
1066
1067 return Importer.getToContext().CharTy;
1068
1069 case BuiltinType::WChar_S:
1070 case BuiltinType::WChar_U:
1071 // FIXME: If not in C++, shall we translate to the C equivalent of
1072 // wchar_t?
1073 return Importer.getToContext().WCharTy;
1074 }
1075
1076 llvm_unreachable("Invalid BuiltinType Kind!")::llvm::llvm_unreachable_internal("Invalid BuiltinType Kind!"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 1076)
;
1077}
1078
1079ExpectedType ASTNodeImporter::VisitDecayedType(const DecayedType *T) {
1080 ExpectedType ToOriginalTypeOrErr = import(T->getOriginalType());
1081 if (!ToOriginalTypeOrErr)
1082 return ToOriginalTypeOrErr.takeError();
1083
1084 return Importer.getToContext().getDecayedType(*ToOriginalTypeOrErr);
1085}
1086
1087ExpectedType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1088 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1089 if (!ToElementTypeOrErr)
1090 return ToElementTypeOrErr.takeError();
1091
1092 return Importer.getToContext().getComplexType(*ToElementTypeOrErr);
1093}
1094
1095ExpectedType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1096 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1097 if (!ToPointeeTypeOrErr)
1098 return ToPointeeTypeOrErr.takeError();
1099
1100 return Importer.getToContext().getPointerType(*ToPointeeTypeOrErr);
1101}
1102
1103ExpectedType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1104 // FIXME: Check for blocks support in "to" context.
1105 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1106 if (!ToPointeeTypeOrErr)
1107 return ToPointeeTypeOrErr.takeError();
1108
1109 return Importer.getToContext().getBlockPointerType(*ToPointeeTypeOrErr);
1110}
1111
1112ExpectedType
1113ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1114 // FIXME: Check for C++ support in "to" context.
1115 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1116 if (!ToPointeeTypeOrErr)
1117 return ToPointeeTypeOrErr.takeError();
1118
1119 return Importer.getToContext().getLValueReferenceType(*ToPointeeTypeOrErr);
1120}
1121
1122ExpectedType
1123ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1124 // FIXME: Check for C++0x support in "to" context.
1125 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1126 if (!ToPointeeTypeOrErr)
1127 return ToPointeeTypeOrErr.takeError();
1128
1129 return Importer.getToContext().getRValueReferenceType(*ToPointeeTypeOrErr);
1130}
1131
1132ExpectedType
1133ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1134 // FIXME: Check for C++ support in "to" context.
1135 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1136 if (!ToPointeeTypeOrErr)
1137 return ToPointeeTypeOrErr.takeError();
1138
1139 ExpectedType ClassTypeOrErr = import(QualType(T->getClass(), 0));
1140 if (!ClassTypeOrErr)
1141 return ClassTypeOrErr.takeError();
1142
1143 return Importer.getToContext().getMemberPointerType(
1144 *ToPointeeTypeOrErr, (*ClassTypeOrErr).getTypePtr());
1145}
1146
1147ExpectedType
1148ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1149 Error Err = Error::success();
1150 auto ToElementType = importChecked(Err, T->getElementType());
1151 auto ToSizeExpr = importChecked(Err, T->getSizeExpr());
1152 if (Err)
1153 return std::move(Err);
1154
1155 return Importer.getToContext().getConstantArrayType(
1156 ToElementType, T->getSize(), ToSizeExpr, T->getSizeModifier(),
1157 T->getIndexTypeCVRQualifiers());
1158}
1159
1160ExpectedType
1161ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1162 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1163 if (!ToElementTypeOrErr)
1164 return ToElementTypeOrErr.takeError();
1165
1166 return Importer.getToContext().getIncompleteArrayType(*ToElementTypeOrErr,
1167 T->getSizeModifier(),
1168 T->getIndexTypeCVRQualifiers());
1169}
1170
1171ExpectedType
1172ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1173 Error Err = Error::success();
1174 QualType ToElementType = importChecked(Err, T->getElementType());
1175 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1176 SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange());
1177 if (Err)
1178 return std::move(Err);
1179 return Importer.getToContext().getVariableArrayType(
1180 ToElementType, ToSizeExpr, T->getSizeModifier(),
1181 T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1182}
1183
1184ExpectedType ASTNodeImporter::VisitDependentSizedArrayType(
1185 const DependentSizedArrayType *T) {
1186 Error Err = Error::success();
1187 QualType ToElementType = importChecked(Err, T->getElementType());
1188 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1189 SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange());
1190 if (Err)
1191 return std::move(Err);
1192 // SizeExpr may be null if size is not specified directly.
1193 // For example, 'int a[]'.
1194
1195 return Importer.getToContext().getDependentSizedArrayType(
1196 ToElementType, ToSizeExpr, T->getSizeModifier(),
1197 T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1198}
1199
1200ExpectedType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1201 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1202 if (!ToElementTypeOrErr)
1203 return ToElementTypeOrErr.takeError();
1204
1205 return Importer.getToContext().getVectorType(*ToElementTypeOrErr,
1206 T->getNumElements(),
1207 T->getVectorKind());
1208}
1209
1210ExpectedType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1211 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1212 if (!ToElementTypeOrErr)
1213 return ToElementTypeOrErr.takeError();
1214
1215 return Importer.getToContext().getExtVectorType(*ToElementTypeOrErr,
1216 T->getNumElements());
1217}
1218
1219ExpectedType
1220ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1221 // FIXME: What happens if we're importing a function without a prototype
1222 // into C++? Should we make it variadic?
1223 ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1224 if (!ToReturnTypeOrErr)
1225 return ToReturnTypeOrErr.takeError();
1226
1227 return Importer.getToContext().getFunctionNoProtoType(*ToReturnTypeOrErr,
1228 T->getExtInfo());
1229}
1230
1231ExpectedType
1232ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1233 ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1234 if (!ToReturnTypeOrErr)
1235 return ToReturnTypeOrErr.takeError();
1236
1237 // Import argument types
1238 SmallVector<QualType, 4> ArgTypes;
1239 for (const auto &A : T->param_types()) {
1240 ExpectedType TyOrErr = import(A);
1241 if (!TyOrErr)
1242 return TyOrErr.takeError();
1243 ArgTypes.push_back(*TyOrErr);
1244 }
1245
1246 // Import exception types
1247 SmallVector<QualType, 4> ExceptionTypes;
1248 for (const auto &E : T->exceptions()) {
1249 ExpectedType TyOrErr = import(E);
1250 if (!TyOrErr)
1251 return TyOrErr.takeError();
1252 ExceptionTypes.push_back(*TyOrErr);
1253 }
1254
1255 FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
1256 Error Err = Error::success();
1257 FunctionProtoType::ExtProtoInfo ToEPI;
1258 ToEPI.ExtInfo = FromEPI.ExtInfo;
1259 ToEPI.Variadic = FromEPI.Variadic;
1260 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1261 ToEPI.TypeQuals = FromEPI.TypeQuals;
1262 ToEPI.RefQualifier = FromEPI.RefQualifier;
1263 ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1264 ToEPI.ExceptionSpec.NoexceptExpr =
1265 importChecked(Err, FromEPI.ExceptionSpec.NoexceptExpr);
1266 ToEPI.ExceptionSpec.SourceDecl =
1267 importChecked(Err, FromEPI.ExceptionSpec.SourceDecl);
1268 ToEPI.ExceptionSpec.SourceTemplate =
1269 importChecked(Err, FromEPI.ExceptionSpec.SourceTemplate);
1270 ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1271
1272 if (Err)
1273 return std::move(Err);
1274
1275 return Importer.getToContext().getFunctionType(
1276 *ToReturnTypeOrErr, ArgTypes, ToEPI);
1277}
1278
1279ExpectedType ASTNodeImporter::VisitUnresolvedUsingType(
1280 const UnresolvedUsingType *T) {
1281 Error Err = Error::success();
1282 auto ToD = importChecked(Err, T->getDecl());
1283 auto ToPrevD = importChecked(Err, T->getDecl()->getPreviousDecl());
1284 if (Err)
1285 return std::move(Err);
1286
1287 return Importer.getToContext().getTypeDeclType(
1288 ToD, cast_or_null<TypeDecl>(ToPrevD));
1289}
1290
1291ExpectedType ASTNodeImporter::VisitParenType(const ParenType *T) {
1292 ExpectedType ToInnerTypeOrErr = import(T->getInnerType());
1293 if (!ToInnerTypeOrErr)
1294 return ToInnerTypeOrErr.takeError();
1295
1296 return Importer.getToContext().getParenType(*ToInnerTypeOrErr);
1297}
1298
1299ExpectedType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1300 Expected<TypedefNameDecl *> ToDeclOrErr = import(T->getDecl());
1301 if (!ToDeclOrErr)
1302 return ToDeclOrErr.takeError();
1303
1304 return Importer.getToContext().getTypeDeclType(*ToDeclOrErr);
1305}
1306
1307ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1308 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1309 if (!ToExprOrErr)
1310 return ToExprOrErr.takeError();
1311
1312 return Importer.getToContext().getTypeOfExprType(*ToExprOrErr);
1313}
1314
1315ExpectedType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1316 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1317 if (!ToUnderlyingTypeOrErr)
1318 return ToUnderlyingTypeOrErr.takeError();
1319
1320 return Importer.getToContext().getTypeOfType(*ToUnderlyingTypeOrErr);
1321}
1322
1323ExpectedType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1324 // FIXME: Make sure that the "to" context supports C++0x!
1325 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1326 if (!ToExprOrErr)
1327 return ToExprOrErr.takeError();
1328
1329 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1330 if (!ToUnderlyingTypeOrErr)
1331 return ToUnderlyingTypeOrErr.takeError();
1332
1333 return Importer.getToContext().getDecltypeType(
1334 *ToExprOrErr, *ToUnderlyingTypeOrErr);
1335}
1336
1337ExpectedType
1338ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1339 ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1340 if (!ToBaseTypeOrErr)
1341 return ToBaseTypeOrErr.takeError();
1342
1343 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1344 if (!ToUnderlyingTypeOrErr)
1345 return ToUnderlyingTypeOrErr.takeError();
1346
1347 return Importer.getToContext().getUnaryTransformType(
1348 *ToBaseTypeOrErr, *ToUnderlyingTypeOrErr, T->getUTTKind());
1349}
1350
1351ExpectedType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1352 // FIXME: Make sure that the "to" context supports C++11!
1353 ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1354 if (!ToDeducedTypeOrErr)
1355 return ToDeducedTypeOrErr.takeError();
1356
1357 ExpectedDecl ToTypeConstraintConcept = import(T->getTypeConstraintConcept());
1358 if (!ToTypeConstraintConcept)
1359 return ToTypeConstraintConcept.takeError();
1360
1361 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1362 ArrayRef<TemplateArgument> FromTemplateArgs = T->getTypeConstraintArguments();
1363 if (Error Err = ImportTemplateArguments(FromTemplateArgs.data(),
1364 FromTemplateArgs.size(),
1365 ToTemplateArgs))
1366 return std::move(Err);
1367
1368 return Importer.getToContext().getAutoType(
1369 *ToDeducedTypeOrErr, T->getKeyword(), /*IsDependent*/false,
1370 /*IsPack=*/false, cast_or_null<ConceptDecl>(*ToTypeConstraintConcept),
1371 ToTemplateArgs);
1372}
1373
1374ExpectedType ASTNodeImporter::VisitInjectedClassNameType(
1375 const InjectedClassNameType *T) {
1376 Expected<CXXRecordDecl *> ToDeclOrErr = import(T->getDecl());
1377 if (!ToDeclOrErr)
1378 return ToDeclOrErr.takeError();
1379
1380 ExpectedType ToInjTypeOrErr = import(T->getInjectedSpecializationType());
1381 if (!ToInjTypeOrErr)
1382 return ToInjTypeOrErr.takeError();
1383
1384 // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading
1385 // See comments in InjectedClassNameType definition for details
1386 // return Importer.getToContext().getInjectedClassNameType(D, InjType);
1387 enum {
1388 TypeAlignmentInBits = 4,
1389 TypeAlignment = 1 << TypeAlignmentInBits
1390 };
1391
1392 return QualType(new (Importer.getToContext(), TypeAlignment)
1393 InjectedClassNameType(*ToDeclOrErr, *ToInjTypeOrErr), 0);
1394}
1395
1396ExpectedType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1397 Expected<RecordDecl *> ToDeclOrErr = import(T->getDecl());
1398 if (!ToDeclOrErr)
1399 return ToDeclOrErr.takeError();
1400
1401 return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1402}
1403
1404ExpectedType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1405 Expected<EnumDecl *> ToDeclOrErr = import(T->getDecl());
1406 if (!ToDeclOrErr)
1407 return ToDeclOrErr.takeError();
1408
1409 return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1410}
1411
1412ExpectedType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
1413 ExpectedType ToModifiedTypeOrErr = import(T->getModifiedType());
1414 if (!ToModifiedTypeOrErr)
1415 return ToModifiedTypeOrErr.takeError();
1416 ExpectedType ToEquivalentTypeOrErr = import(T->getEquivalentType());
1417 if (!ToEquivalentTypeOrErr)
1418 return ToEquivalentTypeOrErr.takeError();
1419
1420 return Importer.getToContext().getAttributedType(T->getAttrKind(),
1421 *ToModifiedTypeOrErr, *ToEquivalentTypeOrErr);
1422}
1423
1424ExpectedType ASTNodeImporter::VisitTemplateTypeParmType(
1425 const TemplateTypeParmType *T) {
1426 Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(T->getDecl());
1427 if (!ToDeclOrErr)
1428 return ToDeclOrErr.takeError();
1429
1430 return Importer.getToContext().getTemplateTypeParmType(
1431 T->getDepth(), T->getIndex(), T->isParameterPack(), *ToDeclOrErr);
1432}
1433
1434ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmType(
1435 const SubstTemplateTypeParmType *T) {
1436 ExpectedType ReplacedOrErr = import(QualType(T->getReplacedParameter(), 0));
1437 if (!ReplacedOrErr)
1438 return ReplacedOrErr.takeError();
1439 const TemplateTypeParmType *Replaced =
1440 cast<TemplateTypeParmType>((*ReplacedOrErr).getTypePtr());
1441
1442 ExpectedType ToReplacementTypeOrErr = import(T->getReplacementType());
1443 if (!ToReplacementTypeOrErr)
1444 return ToReplacementTypeOrErr.takeError();
1445
1446 return Importer.getToContext().getSubstTemplateTypeParmType(
1447 Replaced, (*ToReplacementTypeOrErr).getCanonicalType());
1448}
1449
1450ExpectedType ASTNodeImporter::VisitTemplateSpecializationType(
1451 const TemplateSpecializationType *T) {
1452 auto ToTemplateOrErr = import(T->getTemplateName());
1453 if (!ToTemplateOrErr)
1454 return ToTemplateOrErr.takeError();
1455
1456 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1457 if (Error Err = ImportTemplateArguments(
1458 T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1459 return std::move(Err);
1460
1461 QualType ToCanonType;
1462 if (!QualType(T, 0).isCanonical()) {
1463 QualType FromCanonType
1464 = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1465 if (ExpectedType TyOrErr = import(FromCanonType))
1466 ToCanonType = *TyOrErr;
1467 else
1468 return TyOrErr.takeError();
1469 }
1470 return Importer.getToContext().getTemplateSpecializationType(*ToTemplateOrErr,
1471 ToTemplateArgs,
1472 ToCanonType);
1473}
1474
1475ExpectedType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1476 // Note: the qualifier in an ElaboratedType is optional.
1477 auto ToQualifierOrErr = import(T->getQualifier());
1478 if (!ToQualifierOrErr)
1479 return ToQualifierOrErr.takeError();
1480
1481 ExpectedType ToNamedTypeOrErr = import(T->getNamedType());
1482 if (!ToNamedTypeOrErr)
1483 return ToNamedTypeOrErr.takeError();
1484
1485 Expected<TagDecl *> ToOwnedTagDeclOrErr = import(T->getOwnedTagDecl());
1486 if (!ToOwnedTagDeclOrErr)
1487 return ToOwnedTagDeclOrErr.takeError();
1488
1489 return Importer.getToContext().getElaboratedType(T->getKeyword(),
1490 *ToQualifierOrErr,
1491 *ToNamedTypeOrErr,
1492 *ToOwnedTagDeclOrErr);
1493}
1494
1495ExpectedType
1496ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) {
1497 ExpectedType ToPatternOrErr = import(T->getPattern());
1498 if (!ToPatternOrErr)
1499 return ToPatternOrErr.takeError();
1500
1501 return Importer.getToContext().getPackExpansionType(*ToPatternOrErr,
1502 T->getNumExpansions(),
1503 /*ExpactPack=*/false);
1504}
1505
1506ExpectedType ASTNodeImporter::VisitDependentTemplateSpecializationType(
1507 const DependentTemplateSpecializationType *T) {
1508 auto ToQualifierOrErr = import(T->getQualifier());
1509 if (!ToQualifierOrErr)
1510 return ToQualifierOrErr.takeError();
1511
1512 IdentifierInfo *ToName = Importer.Import(T->getIdentifier());
1513
1514 SmallVector<TemplateArgument, 2> ToPack;
1515 ToPack.reserve(T->getNumArgs());
1516 if (Error Err = ImportTemplateArguments(
1517 T->getArgs(), T->getNumArgs(), ToPack))
1518 return std::move(Err);
1519
1520 return Importer.getToContext().getDependentTemplateSpecializationType(
1521 T->getKeyword(), *ToQualifierOrErr, ToName, ToPack);
1522}
1523
1524ExpectedType
1525ASTNodeImporter::VisitDependentNameType(const DependentNameType *T) {
1526 auto ToQualifierOrErr = import(T->getQualifier());
1527 if (!ToQualifierOrErr)
1528 return ToQualifierOrErr.takeError();
1529
1530 IdentifierInfo *Name = Importer.Import(T->getIdentifier());
1531
1532 QualType Canon;
1533 if (T != T->getCanonicalTypeInternal().getTypePtr()) {
1534 if (ExpectedType TyOrErr = import(T->getCanonicalTypeInternal()))
1535 Canon = (*TyOrErr).getCanonicalType();
1536 else
1537 return TyOrErr.takeError();
1538 }
1539
1540 return Importer.getToContext().getDependentNameType(T->getKeyword(),
1541 *ToQualifierOrErr,
1542 Name, Canon);
1543}
1544
1545ExpectedType
1546ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1547 Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(T->getDecl());
1548 if (!ToDeclOrErr)
1549 return ToDeclOrErr.takeError();
1550
1551 return Importer.getToContext().getObjCInterfaceType(*ToDeclOrErr);
1552}
1553
1554ExpectedType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1555 ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1556 if (!ToBaseTypeOrErr)
1557 return ToBaseTypeOrErr.takeError();
1558
1559 SmallVector<QualType, 4> TypeArgs;
1560 for (auto TypeArg : T->getTypeArgsAsWritten()) {
1561 if (ExpectedType TyOrErr = import(TypeArg))
1562 TypeArgs.push_back(*TyOrErr);
1563 else
1564 return TyOrErr.takeError();
1565 }
1566
1567 SmallVector<ObjCProtocolDecl *, 4> Protocols;
1568 for (auto *P : T->quals()) {
1569 if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(P))
1570 Protocols.push_back(*ProtocolOrErr);
1571 else
1572 return ProtocolOrErr.takeError();
1573
1574 }
1575
1576 return Importer.getToContext().getObjCObjectType(*ToBaseTypeOrErr, TypeArgs,
1577 Protocols,
1578 T->isKindOfTypeAsWritten());
1579}
1580
1581ExpectedType
1582ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1583 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1584 if (!ToPointeeTypeOrErr)
1585 return ToPointeeTypeOrErr.takeError();
1586
1587 return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr);
1588}
1589
1590//----------------------------------------------------------------------------
1591// Import Declarations
1592//----------------------------------------------------------------------------
1593Error ASTNodeImporter::ImportDeclParts(
1594 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
1595 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) {
1596 // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop.
1597 // example: int struct_in_proto(struct data_t{int a;int b;} *d);
1598 // FIXME: We could support these constructs by importing a different type of
1599 // this parameter and by importing the original type of the parameter only
1600 // after the FunctionDecl is created. See
1601 // VisitFunctionDecl::UsedDifferentProtoType.
1602 DeclContext *OrigDC = D->getDeclContext();
1603 FunctionDecl *FunDecl;
1604 if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) &&
6
Assuming 'D' is not a 'RecordDecl'
1605 FunDecl->hasBody()) {
1606 auto getLeafPointeeType = [](const Type *T) {
1607 while (T->isPointerType() || T->isArrayType()) {
1608 T = T->getPointeeOrArrayElementType();
1609 }
1610 return T;
1611 };
1612 for (const ParmVarDecl *P : FunDecl->parameters()) {
1613 const Type *LeafT =
1614 getLeafPointeeType(P->getType().getCanonicalType().getTypePtr());
1615 auto *RT = dyn_cast<RecordType>(LeafT);
1616 if (RT && RT->getDecl() == D) {
1617 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1618 << D->getDeclKindName();
1619 return make_error<ImportError>(ImportError::UnsupportedConstruct);
1620 }
1621 }
1622 }
1623
1624 // Import the context of this declaration.
1625 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
7
Calling 'ASTNodeImporter::ImportDeclContext'
10
Returning from 'ASTNodeImporter::ImportDeclContext'
11
Assuming the condition is false
12
Taking false branch
1626 return Err;
1627
1628 // Import the name of this declaration.
1629 if (Error Err = importInto(Name, D->getDeclName()))
13
Calling 'Error::operator bool'
15
Returning from 'Error::operator bool'
16
Taking false branch
1630 return Err;
1631
1632 // Import the location of this declaration.
1633 if (Error Err = importInto(Loc, D->getLocation()))
17
Assuming the condition is false
18
Taking false branch
1634 return Err;
1635
1636 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
19
Assuming null pointer is passed into cast
20
Null pointer value stored to 'ToD', which participates in a condition later
1637 if (ToD
20.1
'ToD' is null
20.1
'ToD' is null
)
21
Taking false branch
1638 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1639 return Err;
1640
1641 return Error::success();
22
Returning without writing to 'DC'
1642}
1643
1644Error ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclarationName &Name,
1645 NamedDecl *&ToD, SourceLocation &Loc) {
1646
1647 // Import the name of this declaration.
1648 if (Error Err = importInto(Name, D->getDeclName()))
1649 return Err;
1650
1651 // Import the location of this declaration.
1652 if (Error Err = importInto(Loc, D->getLocation()))
1653 return Err;
1654
1655 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1656 if (ToD)
1657 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1658 return Err;
1659
1660 return Error::success();
1661}
1662
1663Error ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
1664 if (!FromD)
1665 return Error::success();
1666
1667 if (!ToD)
1668 if (Error Err = importInto(ToD, FromD))
1669 return Err;
1670
1671 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1672 if (RecordDecl *ToRecord = cast<RecordDecl>(ToD)) {
1673 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() &&
1674 !ToRecord->getDefinition()) {
1675 if (Error Err = ImportDefinition(FromRecord, ToRecord))
1676 return Err;
1677 }
1678 }
1679 return Error::success();
1680 }
1681
1682 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1683 if (EnumDecl *ToEnum = cast<EnumDecl>(ToD)) {
1684 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1685 if (Error Err = ImportDefinition(FromEnum, ToEnum))
1686 return Err;
1687 }
1688 }
1689 return Error::success();
1690 }
1691
1692 return Error::success();
1693}
1694
1695Error
1696ASTNodeImporter::ImportDeclarationNameLoc(
1697 const DeclarationNameInfo &From, DeclarationNameInfo& To) {
1698 // NOTE: To.Name and To.Loc are already imported.
1699 // We only have to import To.LocInfo.
1700 switch (To.getName().getNameKind()) {
1701 case DeclarationName::Identifier:
1702 case DeclarationName::ObjCZeroArgSelector:
1703 case DeclarationName::ObjCOneArgSelector:
1704 case DeclarationName::ObjCMultiArgSelector:
1705 case DeclarationName::CXXUsingDirective:
1706 case DeclarationName::CXXDeductionGuideName:
1707 return Error::success();
1708
1709 case DeclarationName::CXXOperatorName: {
1710 if (auto ToRangeOrErr = import(From.getCXXOperatorNameRange()))
1711 To.setCXXOperatorNameRange(*ToRangeOrErr);
1712 else
1713 return ToRangeOrErr.takeError();
1714 return Error::success();
1715 }
1716 case DeclarationName::CXXLiteralOperatorName: {
1717 if (ExpectedSLoc LocOrErr = import(From.getCXXLiteralOperatorNameLoc()))
1718 To.setCXXLiteralOperatorNameLoc(*LocOrErr);
1719 else
1720 return LocOrErr.takeError();
1721 return Error::success();
1722 }
1723 case DeclarationName::CXXConstructorName:
1724 case DeclarationName::CXXDestructorName:
1725 case DeclarationName::CXXConversionFunctionName: {
1726 if (auto ToTInfoOrErr = import(From.getNamedTypeInfo()))
1727 To.setNamedTypeInfo(*ToTInfoOrErr);
1728 else
1729 return ToTInfoOrErr.takeError();
1730 return Error::success();
1731 }
1732 }
1733 llvm_unreachable("Unknown name kind.")::llvm::llvm_unreachable_internal("Unknown name kind.", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 1733)
;
1734}
1735
1736Error
1737ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
1738 if (Importer.isMinimalImport() && !ForceImport) {
1739 auto ToDCOrErr = Importer.ImportContext(FromDC);
1740 return ToDCOrErr.takeError();
1741 }
1742
1743 // We use strict error handling in case of records and enums, but not
1744 // with e.g. namespaces.
1745 //
1746 // FIXME Clients of the ASTImporter should be able to choose an
1747 // appropriate error handling strategy for their needs. For instance,
1748 // they may not want to mark an entire namespace as erroneous merely
1749 // because there is an ODR error with two typedefs. As another example,
1750 // the client may allow EnumConstantDecls with same names but with
1751 // different values in two distinct translation units.
1752 bool AccumulateChildErrors = isa<TagDecl>(FromDC);
1753
1754 Error ChildErrors = Error::success();
1755 for (auto *From : FromDC->decls()) {
1756 ExpectedDecl ImportedOrErr = import(From);
1757
1758 // If we are in the process of ImportDefinition(...) for a RecordDecl we
1759 // want to make sure that we are also completing each FieldDecl. There
1760 // are currently cases where this does not happen and this is correctness
1761 // fix since operations such as code generation will expect this to be so.
1762 if (ImportedOrErr) {
1763 FieldDecl *FieldFrom = dyn_cast_or_null<FieldDecl>(From);
1764 Decl *ImportedDecl = *ImportedOrErr;
1765 FieldDecl *FieldTo = dyn_cast_or_null<FieldDecl>(ImportedDecl);
1766 if (FieldFrom && FieldTo) {
1767 RecordDecl *FromRecordDecl = nullptr;
1768 RecordDecl *ToRecordDecl = nullptr;
1769 // If we have a field that is an ArrayType we need to check if the array
1770 // element is a RecordDecl and if so we need to import the defintion.
1771 if (FieldFrom->getType()->isArrayType()) {
1772 // getBaseElementTypeUnsafe(...) handles multi-dimensonal arrays for us.
1773 FromRecordDecl = FieldFrom->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl();
1774 ToRecordDecl = FieldTo->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl();
1775 }
1776
1777 if (!FromRecordDecl || !ToRecordDecl) {
1778 const RecordType *RecordFrom =
1779 FieldFrom->getType()->getAs<RecordType>();
1780 const RecordType *RecordTo = FieldTo->getType()->getAs<RecordType>();
1781
1782 if (RecordFrom && RecordTo) {
1783 FromRecordDecl = RecordFrom->getDecl();
1784 ToRecordDecl = RecordTo->getDecl();
1785 }
1786 }
1787
1788 if (FromRecordDecl && ToRecordDecl) {
1789 if (FromRecordDecl->isCompleteDefinition() &&
1790 !ToRecordDecl->isCompleteDefinition()) {
1791 Error Err = ImportDefinition(FromRecordDecl, ToRecordDecl);
1792
1793 if (Err && AccumulateChildErrors)
1794 ChildErrors = joinErrors(std::move(ChildErrors), std::move(Err));
1795 else
1796 consumeError(std::move(Err));
1797 }
1798 }
1799 }
1800 } else {
1801 if (AccumulateChildErrors)
1802 ChildErrors =
1803 joinErrors(std::move(ChildErrors), ImportedOrErr.takeError());
1804 else
1805 consumeError(ImportedOrErr.takeError());
1806 }
1807 }
1808
1809 // We reorder declarations in RecordDecls because they may have another order
1810 // in the "to" context than they have in the "from" context. This may happen
1811 // e.g when we import a class like this:
1812 // struct declToImport {
1813 // int a = c + b;
1814 // int b = 1;
1815 // int c = 2;
1816 // };
1817 // During the import of `a` we import first the dependencies in sequence,
1818 // thus the order would be `c`, `b`, `a`. We will get the normal order by
1819 // first removing the already imported members and then adding them in the
1820 // order as they apper in the "from" context.
1821 //
1822 // Keeping field order is vital because it determines structure layout.
1823 //
1824 // Here and below, we cannot call field_begin() method and its callers on
1825 // ToDC if it has an external storage. Calling field_begin() will
1826 // automatically load all the fields by calling
1827 // LoadFieldsFromExternalStorage(). LoadFieldsFromExternalStorage() would
1828 // call ASTImporter::Import(). This is because the ExternalASTSource
1829 // interface in LLDB is implemented by the means of the ASTImporter. However,
1830 // calling an import at this point would result in an uncontrolled import, we
1831 // must avoid that.
1832 const auto *FromRD = dyn_cast<RecordDecl>(FromDC);
1833 if (!FromRD)
1834 return ChildErrors;
1835
1836 auto ToDCOrErr = Importer.ImportContext(FromDC);
1837 if (!ToDCOrErr) {
1838 consumeError(std::move(ChildErrors));
1839 return ToDCOrErr.takeError();
1840 }
1841
1842 DeclContext *ToDC = *ToDCOrErr;
1843 // Remove all declarations, which may be in wrong order in the
1844 // lexical DeclContext and then add them in the proper order.
1845 for (auto *D : FromRD->decls()) {
1846 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<FriendDecl>(D)) {
1847 assert(D && "DC contains a null decl")((D && "DC contains a null decl") ? static_cast<void
> (0) : __assert_fail ("D && \"DC contains a null decl\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 1847, __PRETTY_FUNCTION__))
;
1848 Decl *ToD = Importer.GetAlreadyImportedOrNull(D);
1849 // Remove only the decls which we successfully imported.
1850 if (ToD) {
1851 assert(ToDC == ToD->getLexicalDeclContext() && ToDC->containsDecl(ToD))((ToDC == ToD->getLexicalDeclContext() && ToDC->
containsDecl(ToD)) ? static_cast<void> (0) : __assert_fail
("ToDC == ToD->getLexicalDeclContext() && ToDC->containsDecl(ToD)"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 1851, __PRETTY_FUNCTION__))
;
1852 // Remove the decl from its wrong place in the linked list.
1853 ToDC->removeDecl(ToD);
1854 // Add the decl to the end of the linked list.
1855 // This time it will be at the proper place because the enclosing for
1856 // loop iterates in the original (good) order of the decls.
1857 ToDC->addDeclInternal(ToD);
1858 }
1859 }
1860 }
1861
1862 return ChildErrors;
1863}
1864
1865Error ASTNodeImporter::ImportDeclContext(
1866 Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) {
1867 auto ToDCOrErr = Importer.ImportContext(FromD->getDeclContext());
1868 if (!ToDCOrErr)
8
Taking true branch
1869 return ToDCOrErr.takeError();
9
Returning without writing to 'ToDC'
1870 ToDC = *ToDCOrErr;
1871
1872 if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) {
1873 auto ToLexicalDCOrErr = Importer.ImportContext(
1874 FromD->getLexicalDeclContext());
1875 if (!ToLexicalDCOrErr)
1876 return ToLexicalDCOrErr.takeError();
1877 ToLexicalDC = *ToLexicalDCOrErr;
1878 } else
1879 ToLexicalDC = ToDC;
1880
1881 return Error::success();
1882}
1883
1884Error ASTNodeImporter::ImportImplicitMethods(
1885 const CXXRecordDecl *From, CXXRecordDecl *To) {
1886 assert(From->isCompleteDefinition() && To->getDefinition() == To &&((From->isCompleteDefinition() && To->getDefinition
() == To && "Import implicit methods to or from non-definition"
) ? static_cast<void> (0) : __assert_fail ("From->isCompleteDefinition() && To->getDefinition() == To && \"Import implicit methods to or from non-definition\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 1887, __PRETTY_FUNCTION__))
1887 "Import implicit methods to or from non-definition")((From->isCompleteDefinition() && To->getDefinition
() == To && "Import implicit methods to or from non-definition"
) ? static_cast<void> (0) : __assert_fail ("From->isCompleteDefinition() && To->getDefinition() == To && \"Import implicit methods to or from non-definition\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 1887, __PRETTY_FUNCTION__))
;
1888
1889 for (CXXMethodDecl *FromM : From->methods())
1890 if (FromM->isImplicit()) {
1891 Expected<CXXMethodDecl *> ToMOrErr = import(FromM);
1892 if (!ToMOrErr)
1893 return ToMOrErr.takeError();
1894 }
1895
1896 return Error::success();
1897}
1898
1899static Error setTypedefNameForAnonDecl(TagDecl *From, TagDecl *To,
1900 ASTImporter &Importer) {
1901 if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) {
1902 if (ExpectedDecl ToTypedefOrErr = Importer.Import(FromTypedef))
1903 To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(*ToTypedefOrErr));
1904 else
1905 return ToTypedefOrErr.takeError();
1906 }
1907 return Error::success();
1908}
1909
1910Error ASTNodeImporter::ImportDefinition(
1911 RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind) {
1912 auto DefinitionCompleter = [To]() {
1913 // There are cases in LLDB when we first import a class without its
1914 // members. The class will have DefinitionData, but no members. Then,
1915 // importDefinition is called from LLDB, which tries to get the members, so
1916 // when we get here, the class already has the DefinitionData set, so we
1917 // must unset the CompleteDefinition here to be able to complete again the
1918 // definition.
1919 To->setCompleteDefinition(false);
1920 To->completeDefinition();
1921 };
1922
1923 if (To->getDefinition() || To->isBeingDefined()) {
1924 if (Kind == IDK_Everything ||
1925 // In case of lambdas, the class already has a definition ptr set, but
1926 // the contained decls are not imported yet. Also, isBeingDefined was
1927 // set in CXXRecordDecl::CreateLambda. We must import the contained
1928 // decls here and finish the definition.
1929 (To->isLambda() && shouldForceImportDeclContext(Kind))) {
1930 if (To->isLambda()) {
1931 auto *FromCXXRD = cast<CXXRecordDecl>(From);
1932 SmallVector<LambdaCapture, 8> ToCaptures;
1933 ToCaptures.reserve(FromCXXRD->capture_size());
1934 for (const auto &FromCapture : FromCXXRD->captures()) {
1935 if (auto ToCaptureOrErr = import(FromCapture))
1936 ToCaptures.push_back(*ToCaptureOrErr);
1937 else
1938 return ToCaptureOrErr.takeError();
1939 }
1940 cast<CXXRecordDecl>(To)->setCaptures(Importer.getToContext(),
1941 ToCaptures);
1942 }
1943
1944 Error Result = ImportDeclContext(From, /*ForceImport=*/true);
1945 // Finish the definition of the lambda, set isBeingDefined to false.
1946 if (To->isLambda())
1947 DefinitionCompleter();
1948 return Result;
1949 }
1950
1951 return Error::success();
1952 }
1953
1954 To->startDefinition();
1955 // Complete the definition even if error is returned.
1956 // The RecordDecl may be already part of the AST so it is better to
1957 // have it in complete state even if something is wrong with it.
1958 auto DefinitionCompleterScopeExit =
1959 llvm::make_scope_exit(DefinitionCompleter);
1960
1961 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
1962 return Err;
1963
1964 // Add base classes.
1965 auto *ToCXX = dyn_cast<CXXRecordDecl>(To);
1966 auto *FromCXX = dyn_cast<CXXRecordDecl>(From);
1967 if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
1968
1969 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
1970 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
1971
1972 #define FIELD(Name, Width, Merge) \
1973 ToData.Name = FromData.Name;
1974 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
1975
1976 // Copy over the data stored in RecordDeclBits
1977 ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions());
1978
1979 SmallVector<CXXBaseSpecifier *, 4> Bases;
1980 for (const auto &Base1 : FromCXX->bases()) {
1981 ExpectedType TyOrErr = import(Base1.getType());
1982 if (!TyOrErr)
1983 return TyOrErr.takeError();
1984
1985 SourceLocation EllipsisLoc;
1986 if (Base1.isPackExpansion()) {
1987 if (ExpectedSLoc LocOrErr = import(Base1.getEllipsisLoc()))
1988 EllipsisLoc = *LocOrErr;
1989 else
1990 return LocOrErr.takeError();
1991 }
1992
1993 // Ensure that we have a definition for the base.
1994 if (Error Err =
1995 ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl()))
1996 return Err;
1997
1998 auto RangeOrErr = import(Base1.getSourceRange());
1999 if (!RangeOrErr)
2000 return RangeOrErr.takeError();
2001
2002 auto TSIOrErr = import(Base1.getTypeSourceInfo());
2003 if (!TSIOrErr)
2004 return TSIOrErr.takeError();
2005
2006 Bases.push_back(
2007 new (Importer.getToContext()) CXXBaseSpecifier(
2008 *RangeOrErr,
2009 Base1.isVirtual(),
2010 Base1.isBaseOfClass(),
2011 Base1.getAccessSpecifierAsWritten(),
2012 *TSIOrErr,
2013 EllipsisLoc));
2014 }
2015 if (!Bases.empty())
2016 ToCXX->setBases(Bases.data(), Bases.size());
2017 }
2018
2019 if (shouldForceImportDeclContext(Kind))
2020 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
2021 return Err;
2022
2023 return Error::success();
2024}
2025
2026Error ASTNodeImporter::ImportInitializer(VarDecl *From, VarDecl *To) {
2027 if (To->getAnyInitializer())
2028 return Error::success();
2029
2030 Expr *FromInit = From->getInit();
2031 if (!FromInit)
2032 return Error::success();
2033
2034 ExpectedExpr ToInitOrErr = import(FromInit);
2035 if (!ToInitOrErr)
2036 return ToInitOrErr.takeError();
2037
2038 To->setInit(*ToInitOrErr);
2039 if (EvaluatedStmt *FromEval = From->getEvaluatedStmt()) {
2040 EvaluatedStmt *ToEval = To->ensureEvaluatedStmt();
2041 ToEval->HasConstantInitialization = FromEval->HasConstantInitialization;
2042 ToEval->HasConstantDestruction = FromEval->HasConstantDestruction;
2043 // FIXME: Also import the initializer value.
2044 }
2045
2046 // FIXME: Other bits to merge?
2047 return Error::success();
2048}
2049
2050Error ASTNodeImporter::ImportDefinition(
2051 EnumDecl *From, EnumDecl *To, ImportDefinitionKind Kind) {
2052 if (To->getDefinition() || To->isBeingDefined()) {
2053 if (Kind == IDK_Everything)
2054 return ImportDeclContext(From, /*ForceImport=*/true);
2055 return Error::success();
2056 }
2057
2058 To->startDefinition();
2059
2060 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
2061 return Err;
2062
2063 ExpectedType ToTypeOrErr =
2064 import(Importer.getFromContext().getTypeDeclType(From));
2065 if (!ToTypeOrErr)
2066 return ToTypeOrErr.takeError();
2067
2068 ExpectedType ToPromotionTypeOrErr = import(From->getPromotionType());
2069 if (!ToPromotionTypeOrErr)
2070 return ToPromotionTypeOrErr.takeError();
2071
2072 if (shouldForceImportDeclContext(Kind))
2073 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
2074 return Err;
2075
2076 // FIXME: we might need to merge the number of positive or negative bits
2077 // if the enumerator lists don't match.
2078 To->completeDefinition(*ToTypeOrErr, *ToPromotionTypeOrErr,
2079 From->getNumPositiveBits(),
2080 From->getNumNegativeBits());
2081 return Error::success();
2082}
2083
2084Error ASTNodeImporter::ImportTemplateArguments(
2085 const TemplateArgument *FromArgs, unsigned NumFromArgs,
2086 SmallVectorImpl<TemplateArgument> &ToArgs) {
2087 for (unsigned I = 0; I != NumFromArgs; ++I) {
2088 if (auto ToOrErr = import(FromArgs[I]))
2089 ToArgs.push_back(*ToOrErr);
2090 else
2091 return ToOrErr.takeError();
2092 }
2093
2094 return Error::success();
2095}
2096
2097// FIXME: Do not forget to remove this and use only 'import'.
2098Expected<TemplateArgument>
2099ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
2100 return import(From);
2101}
2102
2103template <typename InContainerTy>
2104Error ASTNodeImporter::ImportTemplateArgumentListInfo(
2105 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
2106 for (const auto &FromLoc : Container) {
2107 if (auto ToLocOrErr = import(FromLoc))
2108 ToTAInfo.addArgument(*ToLocOrErr);
2109 else
2110 return ToLocOrErr.takeError();
2111 }
2112 return Error::success();
2113}
2114
2115static StructuralEquivalenceKind
2116getStructuralEquivalenceKind(const ASTImporter &Importer) {
2117 return Importer.isMinimalImport() ? StructuralEquivalenceKind::Minimal
2118 : StructuralEquivalenceKind::Default;
2119}
2120
2121bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain) {
2122 StructuralEquivalenceContext Ctx(
2123 Importer.getFromContext(), Importer.getToContext(),
2124 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2125 false, Complain);
2126 return Ctx.IsEquivalent(From, To);
2127}
2128
2129bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
2130 RecordDecl *ToRecord, bool Complain) {
2131 // Eliminate a potential failure point where we attempt to re-import
2132 // something we're trying to import while completing ToRecord.
2133 Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
2134 if (ToOrigin) {
2135 auto *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
2136 if (ToOriginRecord)
2137 ToRecord = ToOriginRecord;
2138 }
2139
2140 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2141 ToRecord->getASTContext(),
2142 Importer.getNonEquivalentDecls(),
2143 getStructuralEquivalenceKind(Importer),
2144 false, Complain);
2145 return Ctx.IsEquivalent(FromRecord, ToRecord);
2146}
2147
2148bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
2149 bool Complain) {
2150 StructuralEquivalenceContext Ctx(
2151 Importer.getFromContext(), Importer.getToContext(),
2152 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2153 false, Complain);
2154 return Ctx.IsEquivalent(FromVar, ToVar);
2155}
2156
2157bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
2158 // Eliminate a potential failure point where we attempt to re-import
2159 // something we're trying to import while completing ToEnum.
2160 if (Decl *ToOrigin = Importer.GetOriginalDecl(ToEnum))
2161 if (auto *ToOriginEnum = dyn_cast<EnumDecl>(ToOrigin))
2162 ToEnum = ToOriginEnum;
2163
2164 StructuralEquivalenceContext Ctx(
2165 Importer.getFromContext(), Importer.getToContext(),
2166 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer));
2167 return Ctx.IsEquivalent(FromEnum, ToEnum);
2168}
2169
2170bool ASTNodeImporter::IsStructuralMatch(FunctionTemplateDecl *From,
2171 FunctionTemplateDecl *To) {
2172 StructuralEquivalenceContext Ctx(
2173 Importer.getFromContext(), Importer.getToContext(),
2174 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2175 false, false);
2176 return Ctx.IsEquivalent(From, To);
2177}
2178
2179bool ASTNodeImporter::IsStructuralMatch(FunctionDecl *From, FunctionDecl *To) {
2180 StructuralEquivalenceContext Ctx(
2181 Importer.getFromContext(), Importer.getToContext(),
2182 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2183 false, false);
2184 return Ctx.IsEquivalent(From, To);
2185}
2186
2187bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
2188 EnumConstantDecl *ToEC) {
2189 const llvm::APSInt &FromVal = FromEC->getInitVal();
2190 const llvm::APSInt &ToVal = ToEC->getInitVal();
2191
2192 return FromVal.isSigned() == ToVal.isSigned() &&
2193 FromVal.getBitWidth() == ToVal.getBitWidth() &&
2194 FromVal == ToVal;
2195}
2196
2197bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
2198 ClassTemplateDecl *To) {
2199 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2200 Importer.getToContext(),
2201 Importer.getNonEquivalentDecls(),
2202 getStructuralEquivalenceKind(Importer));
2203 return Ctx.IsEquivalent(From, To);
2204}
2205
2206bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From,
2207 VarTemplateDecl *To) {
2208 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2209 Importer.getToContext(),
2210 Importer.getNonEquivalentDecls(),
2211 getStructuralEquivalenceKind(Importer));
2212 return Ctx.IsEquivalent(From, To);
2213}
2214
2215ExpectedDecl ASTNodeImporter::VisitDecl(Decl *D) {
2216 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2217 << D->getDeclKindName();
2218 return make_error<ImportError>(ImportError::UnsupportedConstruct);
2219}
2220
2221ExpectedDecl ASTNodeImporter::VisitImportDecl(ImportDecl *D) {
2222 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2223 << D->getDeclKindName();
2224 return make_error<ImportError>(ImportError::UnsupportedConstruct);
2225}
2226
2227ExpectedDecl ASTNodeImporter::VisitEmptyDecl(EmptyDecl *D) {
2228 // Import the context of this declaration.
2229 DeclContext *DC, *LexicalDC;
2230 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
2231 return std::move(Err);
2232
2233 // Import the location of this declaration.
2234 ExpectedSLoc LocOrErr = import(D->getLocation());
2235 if (!LocOrErr)
2236 return LocOrErr.takeError();
2237
2238 EmptyDecl *ToD;
2239 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, *LocOrErr))
2240 return ToD;
2241
2242 ToD->setLexicalDeclContext(LexicalDC);
2243 LexicalDC->addDeclInternal(ToD);
2244 return ToD;
2245}
2246
2247ExpectedDecl ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
2248 TranslationUnitDecl *ToD =
2249 Importer.getToContext().getTranslationUnitDecl();
2250
2251 Importer.MapImported(D, ToD);
2252
2253 return ToD;
2254}
2255
2256ExpectedDecl ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) {
2257 ExpectedSLoc LocOrErr = import(D->getLocation());
2258 if (!LocOrErr)
2259 return LocOrErr.takeError();
2260 auto ColonLocOrErr = import(D->getColonLoc());
2261 if (!ColonLocOrErr)
2262 return ColonLocOrErr.takeError();
2263
2264 // Import the context of this declaration.
2265 auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2266 if (!DCOrErr)
2267 return DCOrErr.takeError();
2268 DeclContext *DC = *DCOrErr;
2269
2270 AccessSpecDecl *ToD;
2271 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(),
2272 DC, *LocOrErr, *ColonLocOrErr))
2273 return ToD;
2274
2275 // Lexical DeclContext and Semantic DeclContext
2276 // is always the same for the accessSpec.
2277 ToD->setLexicalDeclContext(DC);
2278 DC->addDeclInternal(ToD);
2279
2280 return ToD;
2281}
2282
2283ExpectedDecl ASTNodeImporter::VisitStaticAssertDecl(StaticAssertDecl *D) {
2284 auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2285 if (!DCOrErr)
2286 return DCOrErr.takeError();
2287 DeclContext *DC = *DCOrErr;
2288 DeclContext *LexicalDC = DC;
2289
2290 Error Err = Error::success();
2291 auto ToLocation = importChecked(Err, D->getLocation());
2292 auto ToRParenLoc = importChecked(Err, D->getRParenLoc());
2293 auto ToAssertExpr = importChecked(Err, D->getAssertExpr());
2294 auto ToMessage = importChecked(Err, D->getMessage());
2295 if (Err)
2296 return std::move(Err);
2297
2298 StaticAssertDecl *ToD;
2299 if (GetImportedOrCreateDecl(
2300 ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage,
2301 ToRParenLoc, D->isFailed()))
2302 return ToD;
2303
2304 ToD->setLexicalDeclContext(LexicalDC);
2305 LexicalDC->addDeclInternal(ToD);
2306 return ToD;
2307}
2308
2309ExpectedDecl ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
2310 // Import the major distinguishing characteristics of this namespace.
2311 DeclContext *DC, *LexicalDC;
2312 DeclarationName Name;
2313 SourceLocation Loc;
2314 NamedDecl *ToD;
2315 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2316 return std::move(Err);
2317 if (ToD)
2318 return ToD;
2319
2320 NamespaceDecl *MergeWithNamespace = nullptr;
2321 if (!Name) {
2322 // This is an anonymous namespace. Adopt an existing anonymous
2323 // namespace if we can.
2324 // FIXME: Not testable.
2325 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2326 MergeWithNamespace = TU->getAnonymousNamespace();
2327 else
2328 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2329 } else {
2330 SmallVector<NamedDecl *, 4> ConflictingDecls;
2331 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2332 for (auto *FoundDecl : FoundDecls) {
2333 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Namespace))
2334 continue;
2335
2336 if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) {
2337 MergeWithNamespace = FoundNS;
2338 ConflictingDecls.clear();
2339 break;
2340 }
2341
2342 ConflictingDecls.push_back(FoundDecl);
2343 }
2344
2345 if (!ConflictingDecls.empty()) {
2346 ExpectedName NameOrErr = Importer.HandleNameConflict(
2347 Name, DC, Decl::IDNS_Namespace, ConflictingDecls.data(),
2348 ConflictingDecls.size());
2349 if (NameOrErr)
2350 Name = NameOrErr.get();
2351 else
2352 return NameOrErr.takeError();
2353 }
2354 }
2355
2356 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2357 if (!BeginLocOrErr)
2358 return BeginLocOrErr.takeError();
2359 ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
2360 if (!RBraceLocOrErr)
2361 return RBraceLocOrErr.takeError();
2362
2363 // Create the "to" namespace, if needed.
2364 NamespaceDecl *ToNamespace = MergeWithNamespace;
2365 if (!ToNamespace) {
2366 if (GetImportedOrCreateDecl(
2367 ToNamespace, D, Importer.getToContext(), DC, D->isInline(),
2368 *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
2369 /*PrevDecl=*/nullptr))
2370 return ToNamespace;
2371 ToNamespace->setRBraceLoc(*RBraceLocOrErr);
2372 ToNamespace->setLexicalDeclContext(LexicalDC);
2373 LexicalDC->addDeclInternal(ToNamespace);
2374
2375 // If this is an anonymous namespace, register it as the anonymous
2376 // namespace within its context.
2377 if (!Name) {
2378 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2379 TU->setAnonymousNamespace(ToNamespace);
2380 else
2381 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2382 }
2383 }
2384 Importer.MapImported(D, ToNamespace);
2385
2386 if (Error Err = ImportDeclContext(D))
2387 return std::move(Err);
2388
2389 return ToNamespace;
2390}
2391
2392ExpectedDecl ASTNodeImporter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
2393 // Import the major distinguishing characteristics of this namespace.
2394 DeclContext *DC, *LexicalDC;
2395 DeclarationName Name;
2396 SourceLocation Loc;
2397 NamedDecl *LookupD;
2398 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc))
2399 return std::move(Err);
2400 if (LookupD)
2401 return LookupD;
2402
2403 // NOTE: No conflict resolution is done for namespace aliases now.
2404
2405 Error Err = Error::success();
2406 auto ToNamespaceLoc = importChecked(Err, D->getNamespaceLoc());
2407 auto ToAliasLoc = importChecked(Err, D->getAliasLoc());
2408 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
2409 auto ToTargetNameLoc = importChecked(Err, D->getTargetNameLoc());
2410 auto ToNamespace = importChecked(Err, D->getNamespace());
2411 if (Err)
2412 return std::move(Err);
2413
2414 IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier());
2415
2416 NamespaceAliasDecl *ToD;
2417 if (GetImportedOrCreateDecl(
2418 ToD, D, Importer.getToContext(), DC, ToNamespaceLoc, ToAliasLoc,
2419 ToIdentifier, ToQualifierLoc, ToTargetNameLoc, ToNamespace))
2420 return ToD;
2421
2422 ToD->setLexicalDeclContext(LexicalDC);
2423 LexicalDC->addDeclInternal(ToD);
2424
2425 return ToD;
2426}
2427
2428ExpectedDecl
2429ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
2430 // Import the major distinguishing characteristics of this typedef.
2431 DeclarationName Name;
2432 SourceLocation Loc;
2433 NamedDecl *ToD;
2434 // Do not import the DeclContext, we will import it once the TypedefNameDecl
2435 // is created.
2436 if (Error Err = ImportDeclParts(D, Name, ToD, Loc))
2437 return std::move(Err);
2438 if (ToD)
2439 return ToD;
2440
2441 DeclContext *DC = cast_or_null<DeclContext>(
2442 Importer.GetAlreadyImportedOrNull(cast<Decl>(D->getDeclContext())));
2443 DeclContext *LexicalDC =
2444 cast_or_null<DeclContext>(Importer.GetAlreadyImportedOrNull(
2445 cast<Decl>(D->getLexicalDeclContext())));
2446
2447 // If this typedef is not in block scope, determine whether we've
2448 // seen a typedef with the same name (that we can merge with) or any
2449 // other entity by that name (which name lookup could conflict with).
2450 // Note: Repeated typedefs are not valid in C99:
2451 // 'typedef int T; typedef int T;' is invalid
2452 // We do not care about this now.
2453 if (DC && !DC->isFunctionOrMethod()) {
2454 SmallVector<NamedDecl *, 4> ConflictingDecls;
2455 unsigned IDNS = Decl::IDNS_Ordinary;
2456 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2457 for (auto *FoundDecl : FoundDecls) {
2458 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2459 continue;
2460 if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2461 if (!hasSameVisibilityContextAndLinkage(FoundTypedef, D))
2462 continue;
2463
2464 QualType FromUT = D->getUnderlyingType();
2465 QualType FoundUT = FoundTypedef->getUnderlyingType();
2466 if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) {
2467 // If the "From" context has a complete underlying type but we
2468 // already have a complete underlying type then return with that.
2469 if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType())
2470 return Importer.MapImported(D, FoundTypedef);
2471 // FIXME Handle redecl chain. When you do that make consistent changes
2472 // in ASTImporterLookupTable too.
2473 } else {
2474 ConflictingDecls.push_back(FoundDecl);
2475 }
2476 }
2477 }
2478
2479 if (!ConflictingDecls.empty()) {
2480 ExpectedName NameOrErr = Importer.HandleNameConflict(
2481 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2482 if (NameOrErr)
2483 Name = NameOrErr.get();
2484 else
2485 return NameOrErr.takeError();
2486 }
2487 }
2488
2489 Error Err = Error::success();
2490 auto ToUnderlyingType = importChecked(Err, D->getUnderlyingType());
2491 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
2492 auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
2493 if (Err)
2494 return std::move(Err);
2495
2496 // Create the new typedef node.
2497 // FIXME: ToUnderlyingType is not used.
2498 (void)ToUnderlyingType;
2499 TypedefNameDecl *ToTypedef;
2500 if (IsAlias) {
2501 if (GetImportedOrCreateDecl<TypeAliasDecl>(
2502 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2503 Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2504 return ToTypedef;
2505 } else if (GetImportedOrCreateDecl<TypedefDecl>(
2506 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2507 Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2508 return ToTypedef;
2509
2510 // Import the DeclContext and set it to the Typedef.
2511 if ((Err = ImportDeclContext(D, DC, LexicalDC)))
2512 return std::move(Err);
2513 ToTypedef->setDeclContext(DC);
2514 ToTypedef->setLexicalDeclContext(LexicalDC);
2515 // Add to the lookupTable because we could not do that in MapImported.
2516 Importer.AddToLookupTable(ToTypedef);
2517
2518 ToTypedef->setAccess(D->getAccess());
2519
2520 // Templated declarations should not appear in DeclContext.
2521 TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr;
2522 if (!FromAlias || !FromAlias->getDescribedAliasTemplate())
2523 LexicalDC->addDeclInternal(ToTypedef);
2524
2525 return ToTypedef;
2526}
2527
2528ExpectedDecl ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
2529 return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2530}
2531
2532ExpectedDecl ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
2533 return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2534}
2535
2536ExpectedDecl
2537ASTNodeImporter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2538 // Import the major distinguishing characteristics of this typedef.
2539 DeclContext *DC, *LexicalDC;
2540 DeclarationName Name;
2541 SourceLocation Loc;
2542 NamedDecl *FoundD;
2543 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc))
2544 return std::move(Err);
2545 if (FoundD)
2546 return FoundD;
2547
2548 // If this typedef is not in block scope, determine whether we've
2549 // seen a typedef with the same name (that we can merge with) or any
2550 // other entity by that name (which name lookup could conflict with).
2551 if (!DC->isFunctionOrMethod()) {
2552 SmallVector<NamedDecl *, 4> ConflictingDecls;
2553 unsigned IDNS = Decl::IDNS_Ordinary;
2554 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2555 for (auto *FoundDecl : FoundDecls) {
2556 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2557 continue;
2558 if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl))
2559 return Importer.MapImported(D, FoundAlias);
2560 ConflictingDecls.push_back(FoundDecl);
2561 }
2562
2563 if (!ConflictingDecls.empty()) {
2564 ExpectedName NameOrErr = Importer.HandleNameConflict(
2565 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2566 if (NameOrErr)
2567 Name = NameOrErr.get();
2568 else
2569 return NameOrErr.takeError();
2570 }
2571 }
2572
2573 Error Err = Error::success();
2574 auto ToTemplateParameters = importChecked(Err, D->getTemplateParameters());
2575 auto ToTemplatedDecl = importChecked(Err, D->getTemplatedDecl());
2576 if (Err)
2577 return std::move(Err);
2578
2579 TypeAliasTemplateDecl *ToAlias;
2580 if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc,
2581 Name, ToTemplateParameters, ToTemplatedDecl))
2582 return ToAlias;
2583
2584 ToTemplatedDecl->setDescribedAliasTemplate(ToAlias);
2585
2586 ToAlias->setAccess(D->getAccess());
2587 ToAlias->setLexicalDeclContext(LexicalDC);
2588 LexicalDC->addDeclInternal(ToAlias);
2589 return ToAlias;
2590}
2591
2592ExpectedDecl ASTNodeImporter::VisitLabelDecl(LabelDecl *D) {
2593 // Import the major distinguishing characteristics of this label.
2594 DeclContext *DC, *LexicalDC;
2595 DeclarationName Name;
2596 SourceLocation Loc;
2597 NamedDecl *ToD;
2598 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2599 return std::move(Err);
2600 if (ToD)
2601 return ToD;
2602
2603 assert(LexicalDC->isFunctionOrMethod())((LexicalDC->isFunctionOrMethod()) ? static_cast<void>
(0) : __assert_fail ("LexicalDC->isFunctionOrMethod()", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 2603, __PRETTY_FUNCTION__))
;
2604
2605 LabelDecl *ToLabel;
2606 if (D->isGnuLocal()) {
2607 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2608 if (!BeginLocOrErr)
2609 return BeginLocOrErr.takeError();
2610 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2611 Name.getAsIdentifierInfo(), *BeginLocOrErr))
2612 return ToLabel;
2613
2614 } else {
2615 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2616 Name.getAsIdentifierInfo()))
2617 return ToLabel;
2618
2619 }
2620
2621 Expected<LabelStmt *> ToStmtOrErr = import(D->getStmt());
2622 if (!ToStmtOrErr)
2623 return ToStmtOrErr.takeError();
2624
2625 ToLabel->setStmt(*ToStmtOrErr);
2626 ToLabel->setLexicalDeclContext(LexicalDC);
2627 LexicalDC->addDeclInternal(ToLabel);
2628 return ToLabel;
2629}
2630
2631ExpectedDecl ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2632 // Import the major distinguishing characteristics of this enum.
2633 DeclContext *DC, *LexicalDC;
2634 DeclarationName Name;
2635 SourceLocation Loc;
2636 NamedDecl *ToD;
2637 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2638 return std::move(Err);
2639 if (ToD)
2640 return ToD;
2641
2642 // Figure out what enum name we're looking for.
2643 unsigned IDNS = Decl::IDNS_Tag;
2644 DeclarationName SearchName = Name;
2645 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2646 if (Error Err = importInto(
2647 SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2648 return std::move(Err);
2649 IDNS = Decl::IDNS_Ordinary;
2650 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2651 IDNS |= Decl::IDNS_Ordinary;
2652
2653 // We may already have an enum of the same name; try to find and match it.
2654 EnumDecl *PrevDecl = nullptr;
2655 if (!DC->isFunctionOrMethod() && SearchName) {
2656 SmallVector<NamedDecl *, 4> ConflictingDecls;
2657 auto FoundDecls =
2658 Importer.findDeclsInToCtx(DC, SearchName);
2659 for (auto *FoundDecl : FoundDecls) {
2660 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2661 continue;
2662
2663 if (auto *Typedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2664 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2665 FoundDecl = Tag->getDecl();
2666 }
2667
2668 if (auto *FoundEnum = dyn_cast<EnumDecl>(FoundDecl)) {
2669 if (!hasSameVisibilityContextAndLinkage(FoundEnum, D))
2670 continue;
2671 if (IsStructuralMatch(D, FoundEnum)) {
2672 EnumDecl *FoundDef = FoundEnum->getDefinition();
2673 if (D->isThisDeclarationADefinition() && FoundDef)
2674 return Importer.MapImported(D, FoundDef);
2675 PrevDecl = FoundEnum->getMostRecentDecl();
2676 break;
2677 }
2678 ConflictingDecls.push_back(FoundDecl);
2679 }
2680 }
2681
2682 if (!ConflictingDecls.empty()) {
2683 ExpectedName NameOrErr = Importer.HandleNameConflict(
2684 SearchName, DC, IDNS, ConflictingDecls.data(),
2685 ConflictingDecls.size());
2686 if (NameOrErr)
2687 Name = NameOrErr.get();
2688 else
2689 return NameOrErr.takeError();
2690 }
2691 }
2692
2693 Error Err = Error::success();
2694 auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
2695 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
2696 auto ToIntegerType = importChecked(Err, D->getIntegerType());
2697 auto ToBraceRange = importChecked(Err, D->getBraceRange());
2698 if (Err)
2699 return std::move(Err);
2700
2701 // Create the enum declaration.
2702 EnumDecl *D2;
2703 if (GetImportedOrCreateDecl(
2704 D2, D, Importer.getToContext(), DC, ToBeginLoc,
2705 Loc, Name.getAsIdentifierInfo(), PrevDecl, D->isScoped(),
2706 D->isScopedUsingClassTag(), D->isFixed()))
2707 return D2;
2708
2709 D2->setQualifierInfo(ToQualifierLoc);
2710 D2->setIntegerType(ToIntegerType);
2711 D2->setBraceRange(ToBraceRange);
2712 D2->setAccess(D->getAccess());
2713 D2->setLexicalDeclContext(LexicalDC);
2714 LexicalDC->addDeclInternal(D2);
2715
2716 // Import the definition
2717 if (D->isCompleteDefinition())
2718 if (Error Err = ImportDefinition(D, D2))
2719 return std::move(Err);
2720
2721 return D2;
2722}
2723
2724ExpectedDecl ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
2725 bool IsFriendTemplate = false;
2726 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2727 IsFriendTemplate =
2728 DCXX->getDescribedClassTemplate() &&
2729 DCXX->getDescribedClassTemplate()->getFriendObjectKind() !=
2730 Decl::FOK_None;
2731 }
2732
2733 // Import the major distinguishing characteristics of this record.
2734 DeclContext *DC = nullptr, *LexicalDC = nullptr;
2735 DeclarationName Name;
2736 SourceLocation Loc;
2737 NamedDecl *ToD = nullptr;
2738 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2739 return std::move(Err);
2740 if (ToD)
2741 return ToD;
2742
2743 // Figure out what structure name we're looking for.
2744 unsigned IDNS = Decl::IDNS_Tag;
2745 DeclarationName SearchName = Name;
2746 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2747 if (Error Err = importInto(
2748 SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2749 return std::move(Err);
2750 IDNS = Decl::IDNS_Ordinary;
2751 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2752 IDNS |= Decl::IDNS_Ordinary | Decl::IDNS_TagFriend;
2753
2754 // We may already have a record of the same name; try to find and match it.
2755 RecordDecl *PrevDecl = nullptr;
2756 if (!DC->isFunctionOrMethod() && !D->isLambda()) {
2757 SmallVector<NamedDecl *, 4> ConflictingDecls;
2758 auto FoundDecls =
2759 Importer.findDeclsInToCtx(DC, SearchName);
2760 if (!FoundDecls.empty()) {
2761 // We're going to have to compare D against potentially conflicting Decls,
2762 // so complete it.
2763 if (D->hasExternalLexicalStorage() && !D->isCompleteDefinition())
2764 D->getASTContext().getExternalSource()->CompleteType(D);
2765 }
2766
2767 for (auto *FoundDecl : FoundDecls) {
2768 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2769 continue;
2770
2771 Decl *Found = FoundDecl;
2772 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2773 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2774 Found = Tag->getDecl();
2775 }
2776
2777 if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2778 // Do not emit false positive diagnostic in case of unnamed
2779 // struct/union and in case of anonymous structs. Would be false
2780 // because there may be several anonymous/unnamed structs in a class.
2781 // E.g. these are both valid:
2782 // struct A { // unnamed structs
2783 // struct { struct A *next; } entry0;
2784 // struct { struct A *next; } entry1;
2785 // };
2786 // struct X { struct { int a; }; struct { int b; }; }; // anon structs
2787 if (!SearchName)
2788 if (!IsStructuralMatch(D, FoundRecord, false))
2789 continue;
2790
2791 if (!hasSameVisibilityContextAndLinkage(FoundRecord, D))
2792 continue;
2793
2794 if (IsStructuralMatch(D, FoundRecord)) {
2795 RecordDecl *FoundDef = FoundRecord->getDefinition();
2796 if (D->isThisDeclarationADefinition() && FoundDef) {
2797 // FIXME: Structural equivalence check should check for same
2798 // user-defined methods.
2799 Importer.MapImported(D, FoundDef);
2800 if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2801 auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef);
2802 assert(FoundCXX && "Record type mismatch")((FoundCXX && "Record type mismatch") ? static_cast<
void> (0) : __assert_fail ("FoundCXX && \"Record type mismatch\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 2802, __PRETTY_FUNCTION__))
;
2803
2804 if (!Importer.isMinimalImport())
2805 // FoundDef may not have every implicit method that D has
2806 // because implicit methods are created only if they are used.
2807 if (Error Err = ImportImplicitMethods(DCXX, FoundCXX))
2808 return std::move(Err);
2809 }
2810 }
2811 PrevDecl = FoundRecord->getMostRecentDecl();
2812 break;
2813 }
2814 ConflictingDecls.push_back(FoundDecl);
2815 } // kind is RecordDecl
2816 } // for
2817
2818 if (!ConflictingDecls.empty() && SearchName) {
2819 ExpectedName NameOrErr = Importer.HandleNameConflict(
2820 SearchName, DC, IDNS, ConflictingDecls.data(),
2821 ConflictingDecls.size());
2822 if (NameOrErr)
2823 Name = NameOrErr.get();
2824 else
2825 return NameOrErr.takeError();
2826 }
2827 }
2828
2829 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2830 if (!BeginLocOrErr)
2831 return BeginLocOrErr.takeError();
2832
2833 // Create the record declaration.
2834 RecordDecl *D2 = nullptr;
2835 CXXRecordDecl *D2CXX = nullptr;
2836 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2837 if (DCXX->isLambda()) {
2838 auto TInfoOrErr = import(DCXX->getLambdaTypeInfo());
2839 if (!TInfoOrErr)
2840 return TInfoOrErr.takeError();
2841 if (GetImportedOrCreateSpecialDecl(
2842 D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(),
2843 DC, *TInfoOrErr, Loc, DCXX->isDependentLambda(),
2844 DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault()))
2845 return D2CXX;
2846 ExpectedDecl CDeclOrErr = import(DCXX->getLambdaContextDecl());
2847 if (!CDeclOrErr)
2848 return CDeclOrErr.takeError();
2849 D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), *CDeclOrErr,
2850 DCXX->hasKnownLambdaInternalLinkage());
2851 } else if (DCXX->isInjectedClassName()) {
2852 // We have to be careful to do a similar dance to the one in
2853 // Sema::ActOnStartCXXMemberDeclarations
2854 const bool DelayTypeCreation = true;
2855 if (GetImportedOrCreateDecl(
2856 D2CXX, D, Importer.getToContext(), D->getTagKind(), DC,
2857 *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
2858 cast_or_null<CXXRecordDecl>(PrevDecl), DelayTypeCreation))
2859 return D2CXX;
2860 Importer.getToContext().getTypeDeclType(
2861 D2CXX, dyn_cast<CXXRecordDecl>(DC));
2862 } else {
2863 if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
2864 D->getTagKind(), DC, *BeginLocOrErr, Loc,
2865 Name.getAsIdentifierInfo(),
2866 cast_or_null<CXXRecordDecl>(PrevDecl)))
2867 return D2CXX;
2868 }
2869
2870 D2 = D2CXX;
2871 D2->setAccess(D->getAccess());
2872 D2->setLexicalDeclContext(LexicalDC);
2873 addDeclToContexts(D, D2);
2874
2875 if (ClassTemplateDecl *FromDescribed =
2876 DCXX->getDescribedClassTemplate()) {
2877 ClassTemplateDecl *ToDescribed;
2878 if (Error Err = importInto(ToDescribed, FromDescribed))
2879 return std::move(Err);
2880 D2CXX->setDescribedClassTemplate(ToDescribed);
2881 if (!DCXX->isInjectedClassName() && !IsFriendTemplate) {
2882 // In a record describing a template the type should be an
2883 // InjectedClassNameType (see Sema::CheckClassTemplate). Update the
2884 // previously set type to the correct value here (ToDescribed is not
2885 // available at record create).
2886 // FIXME: The previous type is cleared but not removed from
2887 // ASTContext's internal storage.
2888 CXXRecordDecl *Injected = nullptr;
2889 for (NamedDecl *Found : D2CXX->noload_lookup(Name)) {
2890 auto *Record = dyn_cast<CXXRecordDecl>(Found);
2891 if (Record && Record->isInjectedClassName()) {
2892 Injected = Record;
2893 break;
2894 }
2895 }
2896 // Create an injected type for the whole redecl chain.
2897 SmallVector<Decl *, 2> Redecls =
2898 getCanonicalForwardRedeclChain(D2CXX);
2899 for (auto *R : Redecls) {
2900 auto *RI = cast<CXXRecordDecl>(R);
2901 RI->setTypeForDecl(nullptr);
2902 // Below we create a new injected type and assign that to the
2903 // canonical decl, subsequent declarations in the chain will reuse
2904 // that type.
2905 Importer.getToContext().getInjectedClassNameType(
2906 RI, ToDescribed->getInjectedClassNameSpecialization());
2907 }
2908 // Set the new type for the previous injected decl too.
2909 if (Injected) {
2910 Injected->setTypeForDecl(nullptr);
2911 Importer.getToContext().getTypeDeclType(Injected, D2CXX);
2912 }
2913 }
2914 } else if (MemberSpecializationInfo *MemberInfo =
2915 DCXX->getMemberSpecializationInfo()) {
2916 TemplateSpecializationKind SK =
2917 MemberInfo->getTemplateSpecializationKind();
2918 CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass();
2919
2920 if (Expected<CXXRecordDecl *> ToInstOrErr = import(FromInst))
2921 D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK);
2922 else
2923 return ToInstOrErr.takeError();
2924
2925 if (ExpectedSLoc POIOrErr =
2926 import(MemberInfo->getPointOfInstantiation()))
2927 D2CXX->getMemberSpecializationInfo()->setPointOfInstantiation(
2928 *POIOrErr);
2929 else
2930 return POIOrErr.takeError();
2931 }
2932
2933 } else {
2934 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(),
2935 D->getTagKind(), DC, *BeginLocOrErr, Loc,
2936 Name.getAsIdentifierInfo(), PrevDecl))
2937 return D2;
2938 D2->setLexicalDeclContext(LexicalDC);
2939 addDeclToContexts(D, D2);
2940 }
2941
2942 if (auto BraceRangeOrErr = import(D->getBraceRange()))
2943 D2->setBraceRange(*BraceRangeOrErr);
2944 else
2945 return BraceRangeOrErr.takeError();
2946 if (auto QualifierLocOrErr = import(D->getQualifierLoc()))
2947 D2->setQualifierInfo(*QualifierLocOrErr);
2948 else
2949 return QualifierLocOrErr.takeError();
2950
2951 if (D->isAnonymousStructOrUnion())
2952 D2->setAnonymousStructOrUnion(true);
2953
2954 if (D->isCompleteDefinition())
2955 if (Error Err = ImportDefinition(D, D2, IDK_Default))
2956 return std::move(Err);
2957
2958 return D2;
2959}
2960
2961ExpectedDecl ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
2962 // Import the major distinguishing characteristics of this enumerator.
2963 DeclContext *DC, *LexicalDC;
2964 DeclarationName Name;
2965 SourceLocation Loc;
2966 NamedDecl *ToD;
2967 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2968 return std::move(Err);
2969 if (ToD)
2970 return ToD;
2971
2972 // Determine whether there are any other declarations with the same name and
2973 // in the same context.
2974 if (!LexicalDC->isFunctionOrMethod()) {
2975 SmallVector<NamedDecl *, 4> ConflictingDecls;
2976 unsigned IDNS = Decl::IDNS_Ordinary;
2977 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2978 for (auto *FoundDecl : FoundDecls) {
2979 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2980 continue;
2981
2982 if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) {
2983 if (IsStructuralMatch(D, FoundEnumConstant))
2984 return Importer.MapImported(D, FoundEnumConstant);
2985 ConflictingDecls.push_back(FoundDecl);
2986 }
2987 }
2988
2989 if (!ConflictingDecls.empty()) {
2990 ExpectedName NameOrErr = Importer.HandleNameConflict(
2991 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2992 if (NameOrErr)
2993 Name = NameOrErr.get();
2994 else
2995 return NameOrErr.takeError();
2996 }
2997 }
2998
2999 ExpectedType TypeOrErr = import(D->getType());
3000 if (!TypeOrErr)
3001 return TypeOrErr.takeError();
3002
3003 ExpectedExpr InitOrErr = import(D->getInitExpr());
3004 if (!InitOrErr)
3005 return InitOrErr.takeError();
3006
3007 EnumConstantDecl *ToEnumerator;
3008 if (GetImportedOrCreateDecl(
3009 ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc,
3010 Name.getAsIdentifierInfo(), *TypeOrErr, *InitOrErr, D->getInitVal()))
3011 return ToEnumerator;
3012
3013 ToEnumerator->setAccess(D->getAccess());
3014 ToEnumerator->setLexicalDeclContext(LexicalDC);
3015 LexicalDC->addDeclInternal(ToEnumerator);
3016 return ToEnumerator;
3017}
3018
3019Error ASTNodeImporter::ImportTemplateParameterLists(const DeclaratorDecl *FromD,
3020 DeclaratorDecl *ToD) {
3021 unsigned int Num = FromD->getNumTemplateParameterLists();
3022 if (Num == 0)
3023 return Error::success();
3024 SmallVector<TemplateParameterList *, 2> ToTPLists(Num);
3025 for (unsigned int I = 0; I < Num; ++I)
3026 if (Expected<TemplateParameterList *> ToTPListOrErr =
3027 import(FromD->getTemplateParameterList(I)))
3028 ToTPLists[I] = *ToTPListOrErr;
3029 else
3030 return ToTPListOrErr.takeError();
3031 ToD->setTemplateParameterListsInfo(Importer.ToContext, ToTPLists);
3032 return Error::success();
3033}
3034
3035Error ASTNodeImporter::ImportTemplateInformation(
3036 FunctionDecl *FromFD, FunctionDecl *ToFD) {
3037 switch (FromFD->getTemplatedKind()) {
3038 case FunctionDecl::TK_NonTemplate:
3039 case FunctionDecl::TK_FunctionTemplate:
3040 return Error::success();
3041
3042 case FunctionDecl::TK_MemberSpecialization: {
3043 TemplateSpecializationKind TSK = FromFD->getTemplateSpecializationKind();
3044
3045 if (Expected<FunctionDecl *> InstFDOrErr =
3046 import(FromFD->getInstantiatedFromMemberFunction()))
3047 ToFD->setInstantiationOfMemberFunction(*InstFDOrErr, TSK);
3048 else
3049 return InstFDOrErr.takeError();
3050
3051 if (ExpectedSLoc POIOrErr = import(
3052 FromFD->getMemberSpecializationInfo()->getPointOfInstantiation()))
3053 ToFD->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
3054 else
3055 return POIOrErr.takeError();
3056
3057 return Error::success();
3058 }
3059
3060 case FunctionDecl::TK_FunctionTemplateSpecialization: {
3061 auto FunctionAndArgsOrErr =
3062 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
3063 if (!FunctionAndArgsOrErr)
3064 return FunctionAndArgsOrErr.takeError();
3065
3066 TemplateArgumentList *ToTAList = TemplateArgumentList::CreateCopy(
3067 Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr));
3068
3069 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
3070 TemplateArgumentListInfo ToTAInfo;
3071 const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten;
3072 if (FromTAArgsAsWritten)
3073 if (Error Err = ImportTemplateArgumentListInfo(
3074 *FromTAArgsAsWritten, ToTAInfo))
3075 return Err;
3076
3077 ExpectedSLoc POIOrErr = import(FTSInfo->getPointOfInstantiation());
3078 if (!POIOrErr)
3079 return POIOrErr.takeError();
3080
3081 if (Error Err = ImportTemplateParameterLists(FromFD, ToFD))
3082 return Err;
3083
3084 TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind();
3085 ToFD->setFunctionTemplateSpecialization(
3086 std::get<0>(*FunctionAndArgsOrErr), ToTAList, /* InsertPos= */ nullptr,
3087 TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, *POIOrErr);
3088 return Error::success();
3089 }
3090
3091 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
3092 auto *FromInfo = FromFD->getDependentSpecializationInfo();
3093 UnresolvedSet<8> TemplDecls;
3094 unsigned NumTemplates = FromInfo->getNumTemplates();
3095 for (unsigned I = 0; I < NumTemplates; I++) {
3096 if (Expected<FunctionTemplateDecl *> ToFTDOrErr =
3097 import(FromInfo->getTemplate(I)))
3098 TemplDecls.addDecl(*ToFTDOrErr);
3099 else
3100 return ToFTDOrErr.takeError();
3101 }
3102
3103 // Import TemplateArgumentListInfo.
3104 TemplateArgumentListInfo ToTAInfo;
3105 if (Error Err = ImportTemplateArgumentListInfo(
3106 FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(),
3107 llvm::makeArrayRef(
3108 FromInfo->getTemplateArgs(), FromInfo->getNumTemplateArgs()),
3109 ToTAInfo))
3110 return Err;
3111
3112 ToFD->setDependentTemplateSpecialization(Importer.getToContext(),
3113 TemplDecls, ToTAInfo);
3114 return Error::success();
3115 }
3116 }
3117 llvm_unreachable("All cases should be covered!")::llvm::llvm_unreachable_internal("All cases should be covered!"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 3117)
;
3118}
3119
3120Expected<FunctionDecl *>
3121ASTNodeImporter::FindFunctionTemplateSpecialization(FunctionDecl *FromFD) {
3122 auto FunctionAndArgsOrErr =
3123 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
3124 if (!FunctionAndArgsOrErr)
32
Assuming the condition is false
33
Taking false branch
3125 return FunctionAndArgsOrErr.takeError();
3126
3127 FunctionTemplateDecl *Template;
3128 TemplateArgsTy ToTemplArgs;
3129 std::tie(Template, ToTemplArgs) = *FunctionAndArgsOrErr;
3130 void *InsertPos = nullptr;
3131 auto *FoundSpec = Template->findSpecialization(ToTemplArgs, InsertPos);
3132 return FoundSpec;
34
Calling constructor for 'Expected<clang::FunctionDecl *>'
38
Returning from constructor for 'Expected<clang::FunctionDecl *>'
3133}
3134
3135Error ASTNodeImporter::ImportFunctionDeclBody(FunctionDecl *FromFD,
3136 FunctionDecl *ToFD) {
3137 if (Stmt *FromBody = FromFD->getBody()) {
3138 if (ExpectedStmt ToBodyOrErr = import(FromBody))
3139 ToFD->setBody(*ToBodyOrErr);
3140 else
3141 return ToBodyOrErr.takeError();
3142 }
3143 return Error::success();
3144}
3145
3146// Returns true if the given D has a DeclContext up to the TranslationUnitDecl
3147// which is equal to the given DC.
3148static bool isAncestorDeclContextOf(const DeclContext *DC, const Decl *D) {
3149 const DeclContext *DCi = D->getDeclContext();
3150 while (DCi != D->getTranslationUnitDecl()) {
3151 if (DCi == DC)
3152 return true;
3153 DCi = DCi->getParent();
3154 }
3155 return false;
3156}
3157
3158bool ASTNodeImporter::hasAutoReturnTypeDeclaredInside(FunctionDecl *D) {
3159 QualType FromTy = D->getType();
3160 const FunctionProtoType *FromFPT = FromTy->getAs<FunctionProtoType>();
3161 assert(FromFPT && "Must be called on FunctionProtoType")((FromFPT && "Must be called on FunctionProtoType") ?
static_cast<void> (0) : __assert_fail ("FromFPT && \"Must be called on FunctionProtoType\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 3161, __PRETTY_FUNCTION__))
;
3162 if (AutoType *AutoT = FromFPT->getReturnType()->getContainedAutoType()) {
3163 QualType DeducedT = AutoT->getDeducedType();
3164 if (const RecordType *RecordT =
3165 DeducedT.isNull() ? nullptr : dyn_cast<RecordType>(DeducedT)) {
3166 RecordDecl *RD = RecordT->getDecl();
3167 assert(RD)((RD) ? static_cast<void> (0) : __assert_fail ("RD", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 3167, __PRETTY_FUNCTION__))
;
3168 if (isAncestorDeclContextOf(D, RD)) {
3169 assert(RD->getLexicalDeclContext() == RD->getDeclContext())((RD->getLexicalDeclContext() == RD->getDeclContext()) ?
static_cast<void> (0) : __assert_fail ("RD->getLexicalDeclContext() == RD->getDeclContext()"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 3169, __PRETTY_FUNCTION__))
;
3170 return true;
3171 }
3172 }
3173 }
3174 if (const TypedefType *TypedefT =
3175 dyn_cast<TypedefType>(FromFPT->getReturnType())) {
3176 TypedefNameDecl *TD = TypedefT->getDecl();
3177 assert(TD)((TD) ? static_cast<void> (0) : __assert_fail ("TD", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 3177, __PRETTY_FUNCTION__))
;
3178 if (isAncestorDeclContextOf(D, TD)) {
3179 assert(TD->getLexicalDeclContext() == TD->getDeclContext())((TD->getLexicalDeclContext() == TD->getDeclContext()) ?
static_cast<void> (0) : __assert_fail ("TD->getLexicalDeclContext() == TD->getDeclContext()"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 3179, __PRETTY_FUNCTION__))
;
3180 return true;
3181 }
3182 }
3183 return false;
3184}
3185
3186ExplicitSpecifier
3187ASTNodeImporter::importExplicitSpecifier(Error &Err, ExplicitSpecifier ESpec) {
3188 Expr *ExplicitExpr = ESpec.getExpr();
3189 if (ExplicitExpr)
3190 ExplicitExpr = importChecked(Err, ESpec.getExpr());
3191 return ExplicitSpecifier(ExplicitExpr, ESpec.getKind());
3192}
3193
3194ExpectedDecl ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
3195
3196 SmallVector<Decl *, 2> Redecls = getCanonicalForwardRedeclChain(D);
3197 auto RedeclIt = Redecls.begin();
3198 // Import the first part of the decl chain. I.e. import all previous
3199 // declarations starting from the canonical decl.
3200 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
1
Assuming the condition is false
3201 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3202 if (!ToRedeclOrErr)
3203 return ToRedeclOrErr.takeError();
3204 }
3205 assert(*RedeclIt == D)((*RedeclIt == D) ? static_cast<void> (0) : __assert_fail
("*RedeclIt == D", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 3205, __PRETTY_FUNCTION__))
;
2
Assuming the condition is true
3
'?' condition is true
3206
3207 // Import the major distinguishing characteristics of this function.
3208 DeclContext *DC, *LexicalDC;
4
'DC' declared without an initial value
3209 DeclarationName Name;
3210 SourceLocation Loc;
3211 NamedDecl *ToD;
3212 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5
Calling 'ASTNodeImporter::ImportDeclParts'
23
Returning from 'ASTNodeImporter::ImportDeclParts'
24
Calling 'Error::operator bool'
26
Returning from 'Error::operator bool'
27
Taking false branch
3213 return std::move(Err);
3214 if (ToD
27.1
'ToD' is null
27.1
'ToD' is null
)
28
Taking false branch
3215 return ToD;
3216
3217 FunctionDecl *FoundByLookup = nullptr;
3218 FunctionTemplateDecl *FromFT = D->getDescribedFunctionTemplate();
3219
3220 // If this is a function template specialization, then try to find the same
3221 // existing specialization in the "to" context. The lookup below will not
3222 // find any specialization, but would find the primary template; thus, we
3223 // have to skip normal lookup in case of specializations.
3224 // FIXME handle member function templates (TK_MemberSpecialization) similarly?
3225 if (D->getTemplatedKind() ==
29
Assuming the condition is true
30
Taking true branch
3226 FunctionDecl::TK_FunctionTemplateSpecialization) {
3227 auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(D);
31
Calling 'ASTNodeImporter::FindFunctionTemplateSpecialization'
39
Returning from 'ASTNodeImporter::FindFunctionTemplateSpecialization'
3228 if (!FoundFunctionOrErr)
40
Calling 'Expected::operator bool'
42
Returning from 'Expected::operator bool'
43
Taking false branch
3229 return FoundFunctionOrErr.takeError();
3230 if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) {
44
Assuming 'FoundFunction' is null
45
Taking false branch
3231 if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3232 return Def;
3233 FoundByLookup = FoundFunction;
3234 }
3235 }
3236 // Try to find a function in our own ("to") context with the same name, same
3237 // type, and in the same context as the function we're importing.
3238 else if (!LexicalDC->isFunctionOrMethod()) {
3239 SmallVector<NamedDecl *, 4> ConflictingDecls;
3240 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
3241 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3242 for (auto *FoundDecl : FoundDecls) {
3243 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3244 continue;
3245
3246 if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) {
3247 if (!hasSameVisibilityContextAndLinkage(FoundFunction, D))
3248 continue;
3249
3250 if (IsStructuralMatch(D, FoundFunction)) {
3251 if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3252 return Def;
3253 FoundByLookup = FoundFunction;
3254 break;
3255 }
3256 // FIXME: Check for overloading more carefully, e.g., by boosting
3257 // Sema::IsOverload out to the AST library.
3258
3259 // Function overloading is okay in C++.
3260 if (Importer.getToContext().getLangOpts().CPlusPlus)
3261 continue;
3262
3263 // Complain about inconsistent function types.
3264 Importer.ToDiag(Loc, diag::warn_odr_function_type_inconsistent)
3265 << Name << D->getType() << FoundFunction->getType();
3266 Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here)
3267 << FoundFunction->getType();
3268 ConflictingDecls.push_back(FoundDecl);
3269 }
3270 }
3271
3272 if (!ConflictingDecls.empty()) {
3273 ExpectedName NameOrErr = Importer.HandleNameConflict(
3274 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
3275 if (NameOrErr)
3276 Name = NameOrErr.get();
3277 else
3278 return NameOrErr.takeError();
3279 }
3280 }
3281
3282 // We do not allow more than one in-class declaration of a function. This is
3283 // because AST clients like VTableBuilder asserts on this. VTableBuilder
3284 // assumes there is only one in-class declaration. Building a redecl
3285 // chain would result in more than one in-class declaration for
3286 // overrides (even if they are part of the same redecl chain inside the
3287 // derived class.)
3288 if (FoundByLookup
45.1
'FoundByLookup' is null
45.1
'FoundByLookup' is null
) {
46
Taking false branch
3289 if (isa<CXXMethodDecl>(FoundByLookup)) {
3290 if (D->getLexicalDeclContext() == D->getDeclContext()) {
3291 if (!D->doesThisDeclarationHaveABody()) {
3292 if (FunctionTemplateDecl *DescribedD =
3293 D->getDescribedFunctionTemplate()) {
3294 // Handle a "templated" function together with its described
3295 // template. This avoids need for a similar check at import of the
3296 // described template.
3297 assert(FoundByLookup->getDescribedFunctionTemplate() &&((FoundByLookup->getDescribedFunctionTemplate() &&
"Templated function mapped to non-templated?") ? static_cast
<void> (0) : __assert_fail ("FoundByLookup->getDescribedFunctionTemplate() && \"Templated function mapped to non-templated?\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 3298, __PRETTY_FUNCTION__))
3298 "Templated function mapped to non-templated?")((FoundByLookup->getDescribedFunctionTemplate() &&
"Templated function mapped to non-templated?") ? static_cast
<void> (0) : __assert_fail ("FoundByLookup->getDescribedFunctionTemplate() && \"Templated function mapped to non-templated?\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 3298, __PRETTY_FUNCTION__))
;
3299 Importer.MapImported(DescribedD,
3300 FoundByLookup->getDescribedFunctionTemplate());
3301 }
3302 return Importer.MapImported(D, FoundByLookup);
3303 } else {
3304 // Let's continue and build up the redecl chain in this case.
3305 // FIXME Merge the functions into one decl.
3306 }
3307 }
3308 }
3309 }
3310
3311 DeclarationNameInfo NameInfo(Name, Loc);
3312 // Import additional name location/type info.
3313 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
47
Calling 'Error::operator bool'
49
Returning from 'Error::operator bool'
50
Taking false branch
3314 return std::move(Err);
3315
3316 QualType FromTy = D->getType();
3317 // Set to true if we do not import the type of the function as is. There are
3318 // cases when the original type would result in an infinite recursion during
3319 // the import. To avoid an infinite recursion when importing, we create the
3320 // FunctionDecl with a simplified function type and update it only after the
3321 // relevant AST nodes are already imported.
3322 bool UsedDifferentProtoType = false;
3323 if (const auto *FromFPT
51.1
'FromFPT' is null
51.1
'FromFPT' is null
= FromTy->getAs<FunctionProtoType>()) {
51
Assuming the object is not a 'FunctionProtoType'
52
Taking false branch
3324 QualType FromReturnTy = FromFPT->getReturnType();
3325 // Functions with auto return type may define a struct inside their body
3326 // and the return type could refer to that struct.
3327 // E.g.: auto foo() { struct X{}; return X(); }
3328 // To avoid an infinite recursion when importing, create the FunctionDecl
3329 // with a simplified return type.
3330 if (hasAutoReturnTypeDeclaredInside(D)) {
3331 FromReturnTy = Importer.getFromContext().VoidTy;
3332 UsedDifferentProtoType = true;
3333 }
3334 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
3335 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
3336 // FunctionDecl that we are importing the FunctionProtoType for.
3337 // To avoid an infinite recursion when importing, create the FunctionDecl
3338 // with a simplified function type.
3339 if (FromEPI.ExceptionSpec.SourceDecl ||
3340 FromEPI.ExceptionSpec.SourceTemplate ||
3341 FromEPI.ExceptionSpec.NoexceptExpr) {
3342 FunctionProtoType::ExtProtoInfo DefaultEPI;
3343 FromEPI = DefaultEPI;
3344 UsedDifferentProtoType = true;
3345 }
3346 FromTy = Importer.getFromContext().getFunctionType(
3347 FromReturnTy, FromFPT->getParamTypes(), FromEPI);
3348 }
3349
3350 Error Err = Error::success();
3351 auto T = importChecked(Err, FromTy);
3352 auto TInfo = importChecked(Err, D->getTypeSourceInfo());
3353 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
3354 auto ToEndLoc = importChecked(Err, D->getEndLoc());
3355 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
3356 auto TrailingRequiresClause =
3357 importChecked(Err, D->getTrailingRequiresClause());
3358 if (Err)
53
Assuming the condition is false
54
Taking false branch
3359 return std::move(Err);
3360
3361 // Import the function parameters.
3362 SmallVector<ParmVarDecl *, 8> Parameters;
3363 for (auto P : D->parameters()) {
55
Assuming '__begin1' is equal to '__end1'
3364 if (Expected<ParmVarDecl *> ToPOrErr = import(P))
3365 Parameters.push_back(*ToPOrErr);
3366 else
3367 return ToPOrErr.takeError();
3368 }
3369
3370 // Create the imported function.
3371 FunctionDecl *ToFunction = nullptr;
3372 if (auto *FromConstructor
56.1
'FromConstructor' is null
56.1
'FromConstructor' is null
= dyn_cast<CXXConstructorDecl>(D)) {
56
Assuming 'D' is not a 'CXXConstructorDecl'
57
Taking false branch
3373 ExplicitSpecifier ESpec =
3374 importExplicitSpecifier(Err, FromConstructor->getExplicitSpecifier());
3375 if (Err)
3376 return std::move(Err);
3377 if (GetImportedOrCreateDecl<CXXConstructorDecl>(
3378 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3379 ToInnerLocStart, NameInfo, T, TInfo, ESpec, D->isInlineSpecified(),
3380 D->isImplicit(), D->getConstexprKind(),
3381 InheritedConstructor(), // FIXME: Properly import inherited
3382 // constructor info
3383 TrailingRequiresClause))
3384 return ToFunction;
3385 } else if (CXXDestructorDecl *FromDtor
58.1
'FromDtor' is null
58.1
'FromDtor' is null
= dyn_cast<CXXDestructorDecl>(D)) {
58
Assuming 'D' is not a 'CXXDestructorDecl'
59
Taking false branch
3386
3387 Error Err = Error::success();
3388 auto ToOperatorDelete = importChecked(
3389 Err, const_cast<FunctionDecl *>(FromDtor->getOperatorDelete()));
3390 auto ToThisArg = importChecked(Err, FromDtor->getOperatorDeleteThisArg());
3391 if (Err)
3392 return std::move(Err);
3393
3394 if (GetImportedOrCreateDecl<CXXDestructorDecl>(
3395 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3396 ToInnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(),
3397 D->isImplicit(), D->getConstexprKind(), TrailingRequiresClause))
3398 return ToFunction;
3399
3400 CXXDestructorDecl *ToDtor = cast<CXXDestructorDecl>(ToFunction);
3401
3402 ToDtor->setOperatorDelete(ToOperatorDelete, ToThisArg);
3403 } else if (CXXConversionDecl *FromConversion
60.1
'FromConversion' is null
60.1
'FromConversion' is null
=
61
Taking false branch
3404 dyn_cast<CXXConversionDecl>(D)) {
60
Assuming 'D' is not a 'CXXConversionDecl'
3405 ExplicitSpecifier ESpec =
3406 importExplicitSpecifier(Err, FromConversion->getExplicitSpecifier());
3407 if (Err)
3408 return std::move(Err);
3409 if (GetImportedOrCreateDecl<CXXConversionDecl>(
3410 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3411 ToInnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(), ESpec,
3412 D->getConstexprKind(), SourceLocation(), TrailingRequiresClause))
3413 return ToFunction;
3414 } else if (auto *Method
62.1
'Method' is non-null
62.1
'Method' is non-null
= dyn_cast<CXXMethodDecl>(D)) {
62
Assuming 'D' is a 'CXXMethodDecl'
63
Taking true branch
3415 if (GetImportedOrCreateDecl<CXXMethodDecl>(
3416 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
64
1st function call argument is an uninitialized value
3417 ToInnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(),
3418 Method->isInlineSpecified(), D->getConstexprKind(),
3419 SourceLocation(), TrailingRequiresClause))
3420 return ToFunction;
3421 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(D)) {
3422 ExplicitSpecifier ESpec =
3423 importExplicitSpecifier(Err, Guide->getExplicitSpecifier());
3424 if (Err)
3425 return std::move(Err);
3426 if (GetImportedOrCreateDecl<CXXDeductionGuideDecl>(
3427 ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart, ESpec,
3428 NameInfo, T, TInfo, ToEndLoc))
3429 return ToFunction;
3430 cast<CXXDeductionGuideDecl>(ToFunction)
3431 ->setIsCopyDeductionCandidate(Guide->isCopyDeductionCandidate());
3432 } else {
3433 if (GetImportedOrCreateDecl(
3434 ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart,
3435 NameInfo, T, TInfo, D->getStorageClass(), D->isInlineSpecified(),
3436 D->hasWrittenPrototype(), D->getConstexprKind(),
3437 TrailingRequiresClause))
3438 return ToFunction;
3439 }
3440
3441 // Connect the redecl chain.
3442 if (FoundByLookup) {
3443 auto *Recent = const_cast<FunctionDecl *>(
3444 FoundByLookup->getMostRecentDecl());
3445 ToFunction->setPreviousDecl(Recent);
3446 // FIXME Probably we should merge exception specifications. E.g. In the
3447 // "To" context the existing function may have exception specification with
3448 // noexcept-unevaluated, while the newly imported function may have an
3449 // evaluated noexcept. A call to adjustExceptionSpec() on the imported
3450 // decl and its redeclarations may be required.
3451 }
3452
3453 ToFunction->setQualifierInfo(ToQualifierLoc);
3454 ToFunction->setAccess(D->getAccess());
3455 ToFunction->setLexicalDeclContext(LexicalDC);
3456 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
3457 ToFunction->setTrivial(D->isTrivial());
3458 ToFunction->setPure(D->isPure());
3459 ToFunction->setDefaulted(D->isDefaulted());
3460 ToFunction->setExplicitlyDefaulted(D->isExplicitlyDefaulted());
3461 ToFunction->setDeletedAsWritten(D->isDeletedAsWritten());
3462 ToFunction->setRangeEnd(ToEndLoc);
3463
3464 // Set the parameters.
3465 for (auto *Param : Parameters) {
3466 Param->setOwningFunction(ToFunction);
3467 ToFunction->addDeclInternal(Param);
3468 }
3469 ToFunction->setParams(Parameters);
3470
3471 // We need to complete creation of FunctionProtoTypeLoc manually with setting
3472 // params it refers to.
3473 if (TInfo) {
3474 if (auto ProtoLoc =
3475 TInfo->getTypeLoc().IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
3476 for (unsigned I = 0, N = Parameters.size(); I != N; ++I)
3477 ProtoLoc.setParam(I, Parameters[I]);
3478 }
3479 }
3480
3481 // Import the describing template function, if any.
3482 if (FromFT) {
3483 auto ToFTOrErr = import(FromFT);
3484 if (!ToFTOrErr)
3485 return ToFTOrErr.takeError();
3486 }
3487
3488 // Import Ctor initializers.
3489 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3490 if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
3491 SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers);
3492 // Import first, then allocate memory and copy if there was no error.
3493 if (Error Err = ImportContainerChecked(
3494 FromConstructor->inits(), CtorInitializers))
3495 return std::move(Err);
3496 auto **Memory =
3497 new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
3498 std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
3499 auto *ToCtor = cast<CXXConstructorDecl>(ToFunction);
3500 ToCtor->setCtorInitializers(Memory);
3501 ToCtor->setNumCtorInitializers(NumInitializers);
3502 }
3503 }
3504
3505 if (D->doesThisDeclarationHaveABody()) {
3506 Error Err = ImportFunctionDeclBody(D, ToFunction);
3507
3508 if (Err)
3509 return std::move(Err);
3510 }
3511
3512 // Import and set the original type in case we used another type.
3513 if (UsedDifferentProtoType) {
3514 if (ExpectedType TyOrErr = import(D->getType()))
3515 ToFunction->setType(*TyOrErr);
3516 else
3517 return TyOrErr.takeError();
3518 }
3519
3520 // FIXME: Other bits to merge?
3521
3522 // If it is a template, import all related things.
3523 if (Error Err = ImportTemplateInformation(D, ToFunction))
3524 return std::move(Err);
3525
3526 addDeclToContexts(D, ToFunction);
3527
3528 if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D))
3529 if (Error Err = ImportOverriddenMethods(cast<CXXMethodDecl>(ToFunction),
3530 FromCXXMethod))
3531 return std::move(Err);
3532
3533 // Import the rest of the chain. I.e. import all subsequent declarations.
3534 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
3535 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3536 if (!ToRedeclOrErr)
3537 return ToRedeclOrErr.takeError();
3538 }
3539
3540 return ToFunction;
3541}
3542
3543ExpectedDecl ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
3544 return VisitFunctionDecl(D);
3545}
3546
3547ExpectedDecl ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
3548 return VisitCXXMethodDecl(D);
3549}
3550
3551ExpectedDecl ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
3552 return VisitCXXMethodDecl(D);
3553}
3554
3555ExpectedDecl ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
3556 return VisitCXXMethodDecl(D);
3557}
3558
3559ExpectedDecl
3560ASTNodeImporter::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3561 return VisitFunctionDecl(D);
3562}
3563
3564ExpectedDecl ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
3565 // Import the major distinguishing characteristics of a variable.
3566 DeclContext *DC, *LexicalDC;
3567 DeclarationName Name;
3568 SourceLocation Loc;
3569 NamedDecl *ToD;
3570 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3571 return std::move(Err);
3572 if (ToD)
3573 return ToD;
3574
3575 // Determine whether we've already imported this field.
3576 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3577 for (auto *FoundDecl : FoundDecls) {
3578 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecl)) {
3579 // For anonymous fields, match up by index.
3580 if (!Name &&
3581 ASTImporter::getFieldIndex(D) !=
3582 ASTImporter::getFieldIndex(FoundField))
3583 continue;
3584
3585 if (Importer.IsStructurallyEquivalent(D->getType(),
3586 FoundField->getType())) {
3587 Importer.MapImported(D, FoundField);
3588 // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the
3589 // initializer of a FieldDecl might not had been instantiated in the
3590 // "To" context. However, the "From" context might instantiated that,
3591 // thus we have to merge that.
3592 if (Expr *FromInitializer = D->getInClassInitializer()) {
3593 // We don't have yet the initializer set.
3594 if (FoundField->hasInClassInitializer() &&
3595 !FoundField->getInClassInitializer()) {
3596 if (ExpectedExpr ToInitializerOrErr = import(FromInitializer))
3597 FoundField->setInClassInitializer(*ToInitializerOrErr);
3598 else {
3599 // We can't return error here,
3600 // since we already mapped D as imported.
3601 // FIXME: warning message?
3602 consumeError(ToInitializerOrErr.takeError());
3603 return FoundField;
3604 }
3605 }
3606 }
3607 return FoundField;
3608 }
3609
3610 // FIXME: Why is this case not handled with calling HandleNameConflict?
3611 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
3612 << Name << D->getType() << FoundField->getType();
3613 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3614 << FoundField->getType();
3615
3616 return make_error<ImportError>(ImportError::NameConflict);
3617 }
3618 }
3619
3620 Error Err = Error::success();
3621 auto ToType = importChecked(Err, D->getType());
3622 auto ToTInfo = importChecked(Err, D->getTypeSourceInfo());
3623 auto ToBitWidth = importChecked(Err, D->getBitWidth());
3624 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
3625 auto ToInitializer = importChecked(Err, D->getInClassInitializer());
3626 if (Err)
3627 return std::move(Err);
3628
3629 FieldDecl *ToField;
3630 if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC,
3631 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
3632 ToType, ToTInfo, ToBitWidth, D->isMutable(),
3633 D->getInClassInitStyle()))
3634 return ToField;
3635
3636 ToField->setAccess(D->getAccess());
3637 ToField->setLexicalDeclContext(LexicalDC);
3638 if (ToInitializer)
3639 ToField->setInClassInitializer(ToInitializer);
3640 ToField->setImplicit(D->isImplicit());
3641 LexicalDC->addDeclInternal(ToField);
3642 return ToField;
3643}
3644
3645ExpectedDecl ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
3646 // Import the major distinguishing characteristics of a variable.
3647 DeclContext *DC, *LexicalDC;
3648 DeclarationName Name;
3649 SourceLocation Loc;
3650 NamedDecl *ToD;
3651 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3652 return std::move(Err);
3653 if (ToD)
3654 return ToD;
3655
3656 // Determine whether we've already imported this field.
3657 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3658 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3659 if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
3660 // For anonymous indirect fields, match up by index.
3661 if (!Name &&
3662 ASTImporter::getFieldIndex(D) !=
3663 ASTImporter::getFieldIndex(FoundField))
3664 continue;
3665
3666 if (Importer.IsStructurallyEquivalent(D->getType(),
3667 FoundField->getType(),
3668 !Name.isEmpty())) {
3669 Importer.MapImported(D, FoundField);
3670 return FoundField;
3671 }
3672
3673 // If there are more anonymous fields to check, continue.
3674 if (!Name && I < N-1)
3675 continue;
3676
3677 // FIXME: Why is this case not handled with calling HandleNameConflict?
3678 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
3679 << Name << D->getType() << FoundField->getType();
3680 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3681 << FoundField->getType();
3682
3683 return make_error<ImportError>(ImportError::NameConflict);
3684 }
3685 }
3686
3687 // Import the type.
3688 auto TypeOrErr = import(D->getType());
3689 if (!TypeOrErr)
3690 return TypeOrErr.takeError();
3691
3692 auto **NamedChain =
3693 new (Importer.getToContext()) NamedDecl*[D->getChainingSize()];
3694
3695 unsigned i = 0;
3696 for (auto *PI : D->chain())
3697 if (Expected<NamedDecl *> ToD = import(PI))
3698 NamedChain[i++] = *ToD;
3699 else
3700 return ToD.takeError();
3701
3702 llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()};
3703 IndirectFieldDecl *ToIndirectField;
3704 if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC,
3705 Loc, Name.getAsIdentifierInfo(), *TypeOrErr, CH))
3706 // FIXME here we leak `NamedChain` which is allocated before
3707 return ToIndirectField;
3708
3709 ToIndirectField->setAccess(D->getAccess());
3710 ToIndirectField->setLexicalDeclContext(LexicalDC);
3711 LexicalDC->addDeclInternal(ToIndirectField);
3712 return ToIndirectField;
3713}
3714
3715/// Used as return type of getFriendCountAndPosition.
3716struct FriendCountAndPosition {
3717 /// Number of similar looking friends.
3718 unsigned int TotalCount;
3719 /// Index of the specific FriendDecl.
3720 unsigned int IndexOfDecl;
3721};
3722
3723template <class T>
3724static FriendCountAndPosition getFriendCountAndPosition(
3725 const FriendDecl *FD,
3726 llvm::function_ref<T(const FriendDecl *)> GetCanTypeOrDecl) {
3727 unsigned int FriendCount = 0;
3728 llvm::Optional<unsigned int> FriendPosition;
3729 const auto *RD = cast<CXXRecordDecl>(FD->getLexicalDeclContext());
3730
3731 T TypeOrDecl = GetCanTypeOrDecl(FD);
3732
3733 for (const FriendDecl *FoundFriend : RD->friends()) {
3734 if (FoundFriend == FD) {
3735 FriendPosition = FriendCount;
3736 ++FriendCount;
3737 } else if (!FoundFriend->getFriendDecl() == !FD->getFriendDecl() &&
3738 GetCanTypeOrDecl(FoundFriend) == TypeOrDecl) {
3739 ++FriendCount;
3740 }
3741 }
3742
3743 assert(FriendPosition && "Friend decl not found in own parent.")((FriendPosition && "Friend decl not found in own parent."
) ? static_cast<void> (0) : __assert_fail ("FriendPosition && \"Friend decl not found in own parent.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 3743, __PRETTY_FUNCTION__))
;
3744
3745 return {FriendCount, *FriendPosition};
3746}
3747
3748static FriendCountAndPosition getFriendCountAndPosition(const FriendDecl *FD) {
3749 if (FD->getFriendType())
3750 return getFriendCountAndPosition<QualType>(FD, [](const FriendDecl *F) {
3751 if (TypeSourceInfo *TSI = F->getFriendType())
3752 return TSI->getType().getCanonicalType();
3753 llvm_unreachable("Wrong friend object type.")::llvm::llvm_unreachable_internal("Wrong friend object type."
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 3753)
;
3754 });
3755 else
3756 return getFriendCountAndPosition<Decl *>(FD, [](const FriendDecl *F) {
3757 if (Decl *D = F->getFriendDecl())
3758 return D->getCanonicalDecl();
3759 llvm_unreachable("Wrong friend object type.")::llvm::llvm_unreachable_internal("Wrong friend object type."
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 3759)
;
3760 });
3761}
3762
3763ExpectedDecl ASTNodeImporter::VisitFriendDecl(FriendDecl *D) {
3764 // Import the major distinguishing characteristics of a declaration.
3765 DeclContext *DC, *LexicalDC;
3766 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
3767 return std::move(Err);
3768
3769 // Determine whether we've already imported this decl.
3770 // FriendDecl is not a NamedDecl so we cannot use lookup.
3771 // We try to maintain order and count of redundant friend declarations.
3772 const auto *RD = cast<CXXRecordDecl>(DC);
3773 FriendDecl *ImportedFriend = RD->getFirstFriend();
3774 SmallVector<FriendDecl *, 2> ImportedEquivalentFriends;
3775
3776 while (ImportedFriend) {
3777 bool Match = false;
3778 if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) {
3779 Match =
3780 IsStructuralMatch(D->getFriendDecl(), ImportedFriend->getFriendDecl(),
3781 /*Complain=*/false);
3782 } else if (D->getFriendType() && ImportedFriend->getFriendType()) {
3783 Match = Importer.IsStructurallyEquivalent(
3784 D->getFriendType()->getType(),
3785 ImportedFriend->getFriendType()->getType(), /*Complain=*/false);
3786 }
3787 if (Match)
3788 ImportedEquivalentFriends.push_back(ImportedFriend);
3789
3790 ImportedFriend = ImportedFriend->getNextFriend();
3791 }
3792 FriendCountAndPosition CountAndPosition = getFriendCountAndPosition(D);
3793
3794 assert(ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount &&((ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount
&& "Class with non-matching friends is imported, ODR check wrong?"
) ? static_cast<void> (0) : __assert_fail ("ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount && \"Class with non-matching friends is imported, ODR check wrong?\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 3795, __PRETTY_FUNCTION__))
3795 "Class with non-matching friends is imported, ODR check wrong?")((ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount
&& "Class with non-matching friends is imported, ODR check wrong?"
) ? static_cast<void> (0) : __assert_fail ("ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount && \"Class with non-matching friends is imported, ODR check wrong?\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 3795, __PRETTY_FUNCTION__))
;
3796 if (ImportedEquivalentFriends.size() == CountAndPosition.TotalCount)
3797 return Importer.MapImported(
3798 D, ImportedEquivalentFriends[CountAndPosition.IndexOfDecl]);
3799
3800 // Not found. Create it.
3801 // The declarations will be put into order later by ImportDeclContext.
3802 FriendDecl::FriendUnion ToFU;
3803 if (NamedDecl *FriendD = D->getFriendDecl()) {
3804 NamedDecl *ToFriendD;
3805 if (Error Err = importInto(ToFriendD, FriendD))
3806 return std::move(Err);
3807
3808 if (FriendD->getFriendObjectKind() != Decl::FOK_None &&
3809 !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator)))
3810 ToFriendD->setObjectOfFriendDecl(false);
3811
3812 ToFU = ToFriendD;
3813 } else { // The friend is a type, not a decl.
3814 if (auto TSIOrErr = import(D->getFriendType()))
3815 ToFU = *TSIOrErr;
3816 else
3817 return TSIOrErr.takeError();
3818 }
3819
3820 SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
3821 auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>();
3822 for (unsigned I = 0; I < D->NumTPLists; I++) {
3823 if (auto ListOrErr = import(FromTPLists[I]))
3824 ToTPLists[I] = *ListOrErr;
3825 else
3826 return ListOrErr.takeError();
3827 }
3828
3829 auto LocationOrErr = import(D->getLocation());
3830 if (!LocationOrErr)
3831 return LocationOrErr.takeError();
3832 auto FriendLocOrErr = import(D->getFriendLoc());
3833 if (!FriendLocOrErr)
3834 return FriendLocOrErr.takeError();
3835
3836 FriendDecl *FrD;
3837 if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC,
3838 *LocationOrErr, ToFU,
3839 *FriendLocOrErr, ToTPLists))
3840 return FrD;
3841
3842 FrD->setAccess(D->getAccess());
3843 FrD->setLexicalDeclContext(LexicalDC);
3844 LexicalDC->addDeclInternal(FrD);
3845 return FrD;
3846}
3847
3848ExpectedDecl ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
3849 // Import the major distinguishing characteristics of an ivar.
3850 DeclContext *DC, *LexicalDC;
3851 DeclarationName Name;
3852 SourceLocation Loc;
3853 NamedDecl *ToD;
3854 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3855 return std::move(Err);
3856 if (ToD)
3857 return ToD;
3858
3859 // Determine whether we've already imported this ivar
3860 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3861 for (auto *FoundDecl : FoundDecls) {
3862 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) {
3863 if (Importer.IsStructurallyEquivalent(D->getType(),
3864 FoundIvar->getType())) {
3865 Importer.MapImported(D, FoundIvar);
3866 return FoundIvar;
3867 }
3868
3869 Importer.ToDiag(Loc, diag::warn_odr_ivar_type_inconsistent)
3870 << Name << D->getType() << FoundIvar->getType();
3871 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
3872 << FoundIvar->getType();
3873
3874 return make_error<ImportError>(ImportError::NameConflict);
3875 }
3876 }
3877
3878 Error Err = Error::success();
3879 auto ToType = importChecked(Err, D->getType());
3880 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
3881 auto ToBitWidth = importChecked(Err, D->getBitWidth());
3882 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
3883 if (Err)
3884 return std::move(Err);
3885
3886 ObjCIvarDecl *ToIvar;
3887 if (GetImportedOrCreateDecl(
3888 ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC),
3889 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
3890 ToType, ToTypeSourceInfo,
3891 D->getAccessControl(),ToBitWidth, D->getSynthesize()))
3892 return ToIvar;
3893
3894 ToIvar->setLexicalDeclContext(LexicalDC);
3895 LexicalDC->addDeclInternal(ToIvar);
3896 return ToIvar;
3897}
3898
3899ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) {
3900
3901 SmallVector<Decl*, 2> Redecls = getCanonicalForwardRedeclChain(D);
3902 auto RedeclIt = Redecls.begin();
3903 // Import the first part of the decl chain. I.e. import all previous
3904 // declarations starting from the canonical decl.
3905 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
3906 ExpectedDecl RedeclOrErr = import(*RedeclIt);
3907 if (!RedeclOrErr)
3908 return RedeclOrErr.takeError();
3909 }
3910 assert(*RedeclIt == D)((*RedeclIt == D) ? static_cast<void> (0) : __assert_fail
("*RedeclIt == D", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 3910, __PRETTY_FUNCTION__))
;
3911
3912 // Import the major distinguishing characteristics of a variable.
3913 DeclContext *DC, *LexicalDC;
3914 DeclarationName Name;
3915 SourceLocation Loc;
3916 NamedDecl *ToD;
3917 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3918 return std::move(Err);
3919 if (ToD)
3920 return ToD;
3921
3922 // Try to find a variable in our own ("to") context with the same name and
3923 // in the same context as the variable we're importing.
3924 VarDecl *FoundByLookup = nullptr;
3925 if (D->isFileVarDecl()) {
3926 SmallVector<NamedDecl *, 4> ConflictingDecls;
3927 unsigned IDNS = Decl::IDNS_Ordinary;
3928 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3929 for (auto *FoundDecl : FoundDecls) {
3930 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3931 continue;
3932
3933 if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) {
3934 if (!hasSameVisibilityContextAndLinkage(FoundVar, D))
3935 continue;
3936 if (Importer.IsStructurallyEquivalent(D->getType(),
3937 FoundVar->getType())) {
3938
3939 // The VarDecl in the "From" context has a definition, but in the
3940 // "To" context we already have a definition.
3941 VarDecl *FoundDef = FoundVar->getDefinition();
3942 if (D->isThisDeclarationADefinition() && FoundDef)
3943 // FIXME Check for ODR error if the two definitions have
3944 // different initializers?
3945 return Importer.MapImported(D, FoundDef);
3946
3947 // The VarDecl in the "From" context has an initializer, but in the
3948 // "To" context we already have an initializer.
3949 const VarDecl *FoundDInit = nullptr;
3950 if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit))
3951 // FIXME Diagnose ODR error if the two initializers are different?
3952 return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit));
3953
3954 FoundByLookup = FoundVar;
3955 break;
3956 }
3957
3958 const ArrayType *FoundArray
3959 = Importer.getToContext().getAsArrayType(FoundVar->getType());
3960 const ArrayType *TArray
3961 = Importer.getToContext().getAsArrayType(D->getType());
3962 if (FoundArray && TArray) {
3963 if (isa<IncompleteArrayType>(FoundArray) &&
3964 isa<ConstantArrayType>(TArray)) {
3965 // Import the type.
3966 if (auto TyOrErr = import(D->getType()))
3967 FoundVar->setType(*TyOrErr);
3968 else
3969 return TyOrErr.takeError();
3970
3971 FoundByLookup = FoundVar;
3972 break;
3973 } else if (isa<IncompleteArrayType>(TArray) &&
3974 isa<ConstantArrayType>(FoundArray)) {
3975 FoundByLookup = FoundVar;
3976 break;
3977 }
3978 }
3979
3980 Importer.ToDiag(Loc, diag::warn_odr_variable_type_inconsistent)
3981 << Name << D->getType() << FoundVar->getType();
3982 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
3983 << FoundVar->getType();
3984 ConflictingDecls.push_back(FoundDecl);
3985 }
3986 }
3987
3988 if (!ConflictingDecls.empty()) {
3989 ExpectedName NameOrErr = Importer.HandleNameConflict(
3990 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
3991 if (NameOrErr)
3992 Name = NameOrErr.get();
3993 else
3994 return NameOrErr.takeError();
3995 }
3996 }
3997
3998 Error Err = Error::success();
3999 auto ToType = importChecked(Err, D->getType());
4000 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4001 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4002 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4003 if (Err)
4004 return std::move(Err);
4005
4006 // Create the imported variable.
4007 VarDecl *ToVar;
4008 if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC,
4009 ToInnerLocStart, Loc,
4010 Name.getAsIdentifierInfo(),
4011 ToType, ToTypeSourceInfo,
4012 D->getStorageClass()))
4013 return ToVar;
4014
4015 ToVar->setQualifierInfo(ToQualifierLoc);
4016 ToVar->setAccess(D->getAccess());
4017 ToVar->setLexicalDeclContext(LexicalDC);
4018
4019 if (FoundByLookup) {
4020 auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl());
4021 ToVar->setPreviousDecl(Recent);
4022 }
4023
4024 // Import the described template, if any.
4025 if (D->getDescribedVarTemplate()) {
4026 auto ToVTOrErr = import(D->getDescribedVarTemplate());
4027 if (!ToVTOrErr)
4028 return ToVTOrErr.takeError();
4029 }
4030
4031 if (Error Err = ImportInitializer(D, ToVar))
4032 return std::move(Err);
4033
4034 if (D->isConstexpr())
4035 ToVar->setConstexpr(true);
4036
4037 addDeclToContexts(D, ToVar);
4038
4039 // Import the rest of the chain. I.e. import all subsequent declarations.
4040 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
4041 ExpectedDecl RedeclOrErr = import(*RedeclIt);
4042 if (!RedeclOrErr)
4043 return RedeclOrErr.takeError();
4044 }
4045
4046 return ToVar;
4047}
4048
4049ExpectedDecl ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
4050 // Parameters are created in the translation unit's context, then moved
4051 // into the function declaration's context afterward.
4052 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
4053
4054 Error Err = Error::success();
4055 auto ToDeclName = importChecked(Err, D->getDeclName());
4056 auto ToLocation = importChecked(Err, D->getLocation());
4057 auto ToType = importChecked(Err, D->getType());
4058 if (Err)
4059 return std::move(Err);
4060
4061 // Create the imported parameter.
4062 ImplicitParamDecl *ToParm = nullptr;
4063 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
4064 ToLocation, ToDeclName.getAsIdentifierInfo(),
4065 ToType, D->getParameterKind()))
4066 return ToParm;
4067 return ToParm;
4068}
4069
4070Error ASTNodeImporter::ImportDefaultArgOfParmVarDecl(
4071 const ParmVarDecl *FromParam, ParmVarDecl *ToParam) {
4072 ToParam->setHasInheritedDefaultArg(FromParam->hasInheritedDefaultArg());
4073 ToParam->setKNRPromoted(FromParam->isKNRPromoted());
4074
4075 if (FromParam->hasUninstantiatedDefaultArg()) {
4076 if (auto ToDefArgOrErr = import(FromParam->getUninstantiatedDefaultArg()))
4077 ToParam->setUninstantiatedDefaultArg(*ToDefArgOrErr);
4078 else
4079 return ToDefArgOrErr.takeError();
4080 } else if (FromParam->hasUnparsedDefaultArg()) {
4081 ToParam->setUnparsedDefaultArg();
4082 } else if (FromParam->hasDefaultArg()) {
4083 if (auto ToDefArgOrErr = import(FromParam->getDefaultArg()))
4084 ToParam->setDefaultArg(*ToDefArgOrErr);
4085 else
4086 return ToDefArgOrErr.takeError();
4087 }
4088
4089 return Error::success();
4090}
4091
4092ExpectedDecl ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
4093 // Parameters are created in the translation unit's context, then moved
4094 // into the function declaration's context afterward.
4095 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
4096
4097 Error Err = Error::success();
4098 auto ToDeclName = importChecked(Err, D->getDeclName());
4099 auto ToLocation = importChecked(Err, D->getLocation());
4100 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4101 auto ToType = importChecked(Err, D->getType());
4102 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4103 if (Err)
4104 return std::move(Err);
4105
4106 ParmVarDecl *ToParm;
4107 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
4108 ToInnerLocStart, ToLocation,
4109 ToDeclName.getAsIdentifierInfo(), ToType,
4110 ToTypeSourceInfo, D->getStorageClass(),
4111 /*DefaultArg*/ nullptr))
4112 return ToParm;
4113
4114 // Set the default argument. It should be no problem if it was already done.
4115 // Do not import the default expression before GetImportedOrCreateDecl call
4116 // to avoid possible infinite import loop because circular dependency.
4117 if (Error Err = ImportDefaultArgOfParmVarDecl(D, ToParm))
4118 return std::move(Err);
4119
4120 if (D->isObjCMethodParameter()) {
4121 ToParm->setObjCMethodScopeInfo(D->getFunctionScopeIndex());
4122 ToParm->setObjCDeclQualifier(D->getObjCDeclQualifier());
4123 } else {
4124 ToParm->setScopeInfo(D->getFunctionScopeDepth(),
4125 D->getFunctionScopeIndex());
4126 }
4127
4128 return ToParm;
4129}
4130
4131ExpectedDecl ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
4132 // Import the major distinguishing characteristics of a method.
4133 DeclContext *DC, *LexicalDC;
4134 DeclarationName Name;
4135 SourceLocation Loc;
4136 NamedDecl *ToD;
4137 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4138 return std::move(Err);
4139 if (ToD)
4140 return ToD;
4141
4142 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4143 for (auto *FoundDecl : FoundDecls) {
4144 if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) {
4145 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
4146 continue;
4147
4148 // Check return types.
4149 if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
4150 FoundMethod->getReturnType())) {
4151 Importer.ToDiag(Loc, diag::warn_odr_objc_method_result_type_inconsistent)
4152 << D->isInstanceMethod() << Name << D->getReturnType()
4153 << FoundMethod->getReturnType();
4154 Importer.ToDiag(FoundMethod->getLocation(),
4155 diag::note_odr_objc_method_here)
4156 << D->isInstanceMethod() << Name;
4157
4158 return make_error<ImportError>(ImportError::NameConflict);
4159 }
4160
4161 // Check the number of parameters.
4162 if (D->param_size() != FoundMethod->param_size()) {
4163 Importer.ToDiag(Loc, diag::warn_odr_objc_method_num_params_inconsistent)
4164 << D->isInstanceMethod() << Name
4165 << D->param_size() << FoundMethod->param_size();
4166 Importer.ToDiag(FoundMethod->getLocation(),
4167 diag::note_odr_objc_method_here)
4168 << D->isInstanceMethod() << Name;
4169
4170 return make_error<ImportError>(ImportError::NameConflict);
4171 }
4172
4173 // Check parameter types.
4174 for (ObjCMethodDecl::param_iterator P = D->param_begin(),
4175 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
4176 P != PEnd; ++P, ++FoundP) {
4177 if (!Importer.IsStructurallyEquivalent((*P)->getType(),
4178 (*FoundP)->getType())) {
4179 Importer.FromDiag((*P)->getLocation(),
4180 diag::warn_odr_objc_method_param_type_inconsistent)
4181 << D->isInstanceMethod() << Name
4182 << (*P)->getType() << (*FoundP)->getType();
4183 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
4184 << (*FoundP)->getType();
4185
4186 return make_error<ImportError>(ImportError::NameConflict);
4187 }
4188 }
4189
4190 // Check variadic/non-variadic.
4191 // Check the number of parameters.
4192 if (D->isVariadic() != FoundMethod->isVariadic()) {
4193 Importer.ToDiag(Loc, diag::warn_odr_objc_method_variadic_inconsistent)
4194 << D->isInstanceMethod() << Name;
4195 Importer.ToDiag(FoundMethod->getLocation(),
4196 diag::note_odr_objc_method_here)
4197 << D->isInstanceMethod() << Name;
4198
4199 return make_error<ImportError>(ImportError::NameConflict);
4200 }
4201
4202 // FIXME: Any other bits we need to merge?
4203 return Importer.MapImported(D, FoundMethod);
4204 }
4205 }
4206
4207 Error Err = Error::success();
4208 auto ToEndLoc = importChecked(Err, D->getEndLoc());
4209 auto ToReturnType = importChecked(Err, D->getReturnType());
4210 auto ToReturnTypeSourceInfo =
4211 importChecked(Err, D->getReturnTypeSourceInfo());
4212 if (Err)
4213 return std::move(Err);
4214
4215 ObjCMethodDecl *ToMethod;
4216 if (GetImportedOrCreateDecl(
4217 ToMethod, D, Importer.getToContext(), Loc, ToEndLoc,
4218 Name.getObjCSelector(), ToReturnType, ToReturnTypeSourceInfo, DC,
4219 D->isInstanceMethod(), D->isVariadic(), D->isPropertyAccessor(),
4220 D->isSynthesizedAccessorStub(), D->isImplicit(), D->isDefined(),
4221 D->getImplementationControl(), D->hasRelatedResultType()))
4222 return ToMethod;
4223
4224 // FIXME: When we decide to merge method definitions, we'll need to
4225 // deal with implicit parameters.
4226
4227 // Import the parameters
4228 SmallVector<ParmVarDecl *, 5> ToParams;
4229 for (auto *FromP : D->parameters()) {
4230 if (Expected<ParmVarDecl *> ToPOrErr = import(FromP))
4231 ToParams.push_back(*ToPOrErr);
4232 else
4233 return ToPOrErr.takeError();
4234 }
4235
4236 // Set the parameters.
4237 for (auto *ToParam : ToParams) {
4238 ToParam->setOwningFunction(ToMethod);
4239 ToMethod->addDeclInternal(ToParam);
4240 }
4241
4242 SmallVector<SourceLocation, 12> FromSelLocs;
4243 D->getSelectorLocs(FromSelLocs);
4244 SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size());
4245 if (Error Err = ImportContainerChecked(FromSelLocs, ToSelLocs))
4246 return std::move(Err);
4247
4248 ToMethod->setMethodParams(Importer.getToContext(), ToParams, ToSelLocs);
4249
4250 ToMethod->setLexicalDeclContext(LexicalDC);
4251 LexicalDC->addDeclInternal(ToMethod);
4252
4253 // Implicit params are declared when Sema encounters the definition but this
4254 // never happens when the method is imported. Manually declare the implicit
4255 // params now that the MethodDecl knows its class interface.
4256 if (D->getSelfDecl())
4257 ToMethod->createImplicitParams(Importer.getToContext(),
4258 ToMethod->getClassInterface());
4259
4260 return ToMethod;
4261}
4262
4263ExpectedDecl ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
4264 // Import the major distinguishing characteristics of a category.
4265 DeclContext *DC, *LexicalDC;
4266 DeclarationName Name;
4267 SourceLocation Loc;
4268 NamedDecl *ToD;
4269 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4270 return std::move(Err);
4271 if (ToD)
4272 return ToD;
4273
4274 Error Err = Error::success();
4275 auto ToVarianceLoc = importChecked(Err, D->getVarianceLoc());
4276 auto ToLocation = importChecked(Err, D->getLocation());
4277 auto ToColonLoc = importChecked(Err, D->getColonLoc());
4278 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4279 if (Err)
4280 return std::move(Err);
4281
4282 ObjCTypeParamDecl *Result;
4283 if (GetImportedOrCreateDecl(
4284 Result, D, Importer.getToContext(), DC, D->getVariance(),
4285 ToVarianceLoc, D->getIndex(),
4286 ToLocation, Name.getAsIdentifierInfo(),
4287 ToColonLoc, ToTypeSourceInfo))
4288 return Result;
4289
4290 Result->setLexicalDeclContext(LexicalDC);
4291 return Result;
4292}
4293
4294ExpectedDecl ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
4295 // Import the major distinguishing characteristics of a category.
4296 DeclContext *DC, *LexicalDC;
4297 DeclarationName Name;
4298 SourceLocation Loc;
4299 NamedDecl *ToD;
4300 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4301 return std::move(Err);
4302 if (ToD)
4303 return ToD;
4304
4305 ObjCInterfaceDecl *ToInterface;
4306 if (Error Err = importInto(ToInterface, D->getClassInterface()))
4307 return std::move(Err);
4308
4309 // Determine if we've already encountered this category.
4310 ObjCCategoryDecl *MergeWithCategory
4311 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
4312 ObjCCategoryDecl *ToCategory = MergeWithCategory;
4313 if (!ToCategory) {
4314
4315 Error Err = Error::success();
4316 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
4317 auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc());
4318 auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc());
4319 auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc());
4320 if (Err)
4321 return std::move(Err);
4322
4323 if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC,
4324 ToAtStartLoc, Loc,
4325 ToCategoryNameLoc,
4326 Name.getAsIdentifierInfo(), ToInterface,
4327 /*TypeParamList=*/nullptr,
4328 ToIvarLBraceLoc,
4329 ToIvarRBraceLoc))
4330 return ToCategory;
4331
4332 ToCategory->setLexicalDeclContext(LexicalDC);
4333 LexicalDC->addDeclInternal(ToCategory);
4334 // Import the type parameter list after MapImported, to avoid
4335 // loops when bringing in their DeclContext.
4336 if (auto PListOrErr = ImportObjCTypeParamList(D->getTypeParamList()))
4337 ToCategory->setTypeParamList(*PListOrErr);
4338 else
4339 return PListOrErr.takeError();
4340
4341 // Import protocols
4342 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4343 SmallVector<SourceLocation, 4> ProtocolLocs;
4344 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
4345 = D->protocol_loc_begin();
4346 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
4347 FromProtoEnd = D->protocol_end();
4348 FromProto != FromProtoEnd;
4349 ++FromProto, ++FromProtoLoc) {
4350 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4351 Protocols.push_back(*ToProtoOrErr);
4352 else
4353 return ToProtoOrErr.takeError();
4354
4355 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4356 ProtocolLocs.push_back(*ToProtoLocOrErr);
4357 else
4358 return ToProtoLocOrErr.takeError();
4359 }
4360
4361 // FIXME: If we're merging, make sure that the protocol list is the same.
4362 ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
4363 ProtocolLocs.data(), Importer.getToContext());
4364
4365 } else {
4366 Importer.MapImported(D, ToCategory);
4367 }
4368
4369 // Import all of the members of this category.
4370 if (Error Err = ImportDeclContext(D))
4371 return std::move(Err);
4372
4373 // If we have an implementation, import it as well.
4374 if (D->getImplementation()) {
4375 if (Expected<ObjCCategoryImplDecl *> ToImplOrErr =
4376 import(D->getImplementation()))
4377 ToCategory->setImplementation(*ToImplOrErr);
4378 else
4379 return ToImplOrErr.takeError();
4380 }
4381
4382 return ToCategory;
4383}
4384
4385Error ASTNodeImporter::ImportDefinition(
4386 ObjCProtocolDecl *From, ObjCProtocolDecl *To, ImportDefinitionKind Kind) {
4387 if (To->getDefinition()) {
4388 if (shouldForceImportDeclContext(Kind))
4389 if (Error Err = ImportDeclContext(From))
4390 return Err;
4391 return Error::success();
4392 }
4393
4394 // Start the protocol definition
4395 To->startDefinition();
4396
4397 // Import protocols
4398 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4399 SmallVector<SourceLocation, 4> ProtocolLocs;
4400 ObjCProtocolDecl::protocol_loc_iterator FromProtoLoc =
4401 From->protocol_loc_begin();
4402 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
4403 FromProtoEnd = From->protocol_end();
4404 FromProto != FromProtoEnd;
4405 ++FromProto, ++FromProtoLoc) {
4406 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4407 Protocols.push_back(*ToProtoOrErr);
4408 else
4409 return ToProtoOrErr.takeError();
4410
4411 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4412 ProtocolLocs.push_back(*ToProtoLocOrErr);
4413 else
4414 return ToProtoLocOrErr.takeError();
4415
4416 }
4417
4418 // FIXME: If we're merging, make sure that the protocol list is the same.
4419 To->setProtocolList(Protocols.data(), Protocols.size(),
4420 ProtocolLocs.data(), Importer.getToContext());
4421
4422 if (shouldForceImportDeclContext(Kind)) {
4423 // Import all of the members of this protocol.
4424 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4425 return Err;
4426 }
4427 return Error::success();
4428}
4429
4430ExpectedDecl ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
4431 // If this protocol has a definition in the translation unit we're coming
4432 // from, but this particular declaration is not that definition, import the
4433 // definition and map to that.
4434 ObjCProtocolDecl *Definition = D->getDefinition();
4435 if (Definition && Definition != D) {
4436 if (ExpectedDecl ImportedDefOrErr = import(Definition))
4437 return Importer.MapImported(D, *ImportedDefOrErr);
4438 else
4439 return ImportedDefOrErr.takeError();
4440 }
4441
4442 // Import the major distinguishing characteristics of a protocol.
4443 DeclContext *DC, *LexicalDC;
4444 DeclarationName Name;
4445 SourceLocation Loc;
4446 NamedDecl *ToD;
4447 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4448 return std::move(Err);
4449 if (ToD)
4450 return ToD;
4451
4452 ObjCProtocolDecl *MergeWithProtocol = nullptr;
4453 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4454 for (auto *FoundDecl : FoundDecls) {
4455 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
4456 continue;
4457
4458 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl)))
4459 break;
4460 }
4461
4462 ObjCProtocolDecl *ToProto = MergeWithProtocol;
4463 if (!ToProto) {
4464 auto ToAtBeginLocOrErr = import(D->getAtStartLoc());
4465 if (!ToAtBeginLocOrErr)
4466 return ToAtBeginLocOrErr.takeError();
4467
4468 if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC,
4469 Name.getAsIdentifierInfo(), Loc,
4470 *ToAtBeginLocOrErr,
4471 /*PrevDecl=*/nullptr))
4472 return ToProto;
4473 ToProto->setLexicalDeclContext(LexicalDC);
4474 LexicalDC->addDeclInternal(ToProto);
4475 }
4476
4477 Importer.MapImported(D, ToProto);
4478
4479 if (D->isThisDeclarationADefinition())
4480 if (Error Err = ImportDefinition(D, ToProto))
4481 return std::move(Err);
4482
4483 return ToProto;
4484}
4485
4486ExpectedDecl ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
4487 DeclContext *DC, *LexicalDC;
4488 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4489 return std::move(Err);
4490
4491 ExpectedSLoc ExternLocOrErr = import(D->getExternLoc());
4492 if (!ExternLocOrErr)
4493 return ExternLocOrErr.takeError();
4494
4495 ExpectedSLoc LangLocOrErr = import(D->getLocation());
4496 if (!LangLocOrErr)
4497 return LangLocOrErr.takeError();
4498
4499 bool HasBraces = D->hasBraces();
4500
4501 LinkageSpecDecl *ToLinkageSpec;
4502 if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC,
4503 *ExternLocOrErr, *LangLocOrErr,
4504 D->getLanguage(), HasBraces))
4505 return ToLinkageSpec;
4506
4507 if (HasBraces) {
4508 ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
4509 if (!RBraceLocOrErr)
4510 return RBraceLocOrErr.takeError();
4511 ToLinkageSpec->setRBraceLoc(*RBraceLocOrErr);
4512 }
4513
4514 ToLinkageSpec->setLexicalDeclContext(LexicalDC);
4515 LexicalDC->addDeclInternal(ToLinkageSpec);
4516
4517 return ToLinkageSpec;
4518}
4519
4520ExpectedDecl ASTNodeImporter::VisitUsingDecl(UsingDecl *D) {
4521 DeclContext *DC, *LexicalDC;
4522 DeclarationName Name;
4523 SourceLocation Loc;
4524 NamedDecl *ToD = nullptr;
4525 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4526 return std::move(Err);
4527 if (ToD)
4528 return ToD;
4529
4530 Error Err = Error::success();
4531 auto ToLoc = importChecked(Err, D->getNameInfo().getLoc());
4532 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4533 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4534 if (Err)
4535 return std::move(Err);
4536
4537 DeclarationNameInfo NameInfo(Name, ToLoc);
4538 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
4539 return std::move(Err);
4540
4541 UsingDecl *ToUsing;
4542 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
4543 ToUsingLoc, ToQualifierLoc, NameInfo,
4544 D->hasTypename()))
4545 return ToUsing;
4546
4547 ToUsing->setLexicalDeclContext(LexicalDC);
4548 LexicalDC->addDeclInternal(ToUsing);
4549
4550 if (NamedDecl *FromPattern =
4551 Importer.getFromContext().getInstantiatedFromUsingDecl(D)) {
4552 if (Expected<NamedDecl *> ToPatternOrErr = import(FromPattern))
4553 Importer.getToContext().setInstantiatedFromUsingDecl(
4554 ToUsing, *ToPatternOrErr);
4555 else
4556 return ToPatternOrErr.takeError();
4557 }
4558
4559 for (UsingShadowDecl *FromShadow : D->shadows()) {
4560 if (Expected<UsingShadowDecl *> ToShadowOrErr = import(FromShadow))
4561 ToUsing->addShadowDecl(*ToShadowOrErr);
4562 else
4563 // FIXME: We return error here but the definition is already created
4564 // and available with lookups. How to fix this?..
4565 return ToShadowOrErr.takeError();
4566 }
4567 return ToUsing;
4568}
4569
4570ExpectedDecl ASTNodeImporter::VisitUsingShadowDecl(UsingShadowDecl *D) {
4571 DeclContext *DC, *LexicalDC;
4572 DeclarationName Name;
4573 SourceLocation Loc;
4574 NamedDecl *ToD = nullptr;
4575 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4576 return std::move(Err);
4577 if (ToD)
4578 return ToD;
4579
4580 Expected<UsingDecl *> ToUsingOrErr = import(D->getUsingDecl());
4581 if (!ToUsingOrErr)
4582 return ToUsingOrErr.takeError();
4583
4584 Expected<NamedDecl *> ToTargetOrErr = import(D->getTargetDecl());
4585 if (!ToTargetOrErr)
4586 return ToTargetOrErr.takeError();
4587
4588 UsingShadowDecl *ToShadow;
4589 if (GetImportedOrCreateDecl(ToShadow, D, Importer.getToContext(), DC, Loc,
4590 *ToUsingOrErr, *ToTargetOrErr))
4591 return ToShadow;
4592
4593 ToShadow->setLexicalDeclContext(LexicalDC);
4594 ToShadow->setAccess(D->getAccess());
4595
4596 if (UsingShadowDecl *FromPattern =
4597 Importer.getFromContext().getInstantiatedFromUsingShadowDecl(D)) {
4598 if (Expected<UsingShadowDecl *> ToPatternOrErr = import(FromPattern))
4599 Importer.getToContext().setInstantiatedFromUsingShadowDecl(
4600 ToShadow, *ToPatternOrErr);
4601 else
4602 // FIXME: We return error here but the definition is already created
4603 // and available with lookups. How to fix this?..
4604 return ToPatternOrErr.takeError();
4605 }
4606
4607 LexicalDC->addDeclInternal(ToShadow);
4608
4609 return ToShadow;
4610}
4611
4612ExpectedDecl ASTNodeImporter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
4613 DeclContext *DC, *LexicalDC;
4614 DeclarationName Name;
4615 SourceLocation Loc;
4616 NamedDecl *ToD = nullptr;
4617 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4618 return std::move(Err);
4619 if (ToD)
4620 return ToD;
4621
4622 auto ToComAncestorOrErr = Importer.ImportContext(D->getCommonAncestor());
4623 if (!ToComAncestorOrErr)
4624 return ToComAncestorOrErr.takeError();
4625
4626 Error Err = Error::success();
4627 auto ToNominatedNamespace = importChecked(Err, D->getNominatedNamespace());
4628 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4629 auto ToNamespaceKeyLocation =
4630 importChecked(Err, D->getNamespaceKeyLocation());
4631 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4632 auto ToIdentLocation = importChecked(Err, D->getIdentLocation());
4633 if (Err)
4634 return std::move(Err);
4635
4636 UsingDirectiveDecl *ToUsingDir;
4637 if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC,
4638 ToUsingLoc,
4639 ToNamespaceKeyLocation,
4640 ToQualifierLoc,
4641 ToIdentLocation,
4642 ToNominatedNamespace, *ToComAncestorOrErr))
4643 return ToUsingDir;
4644
4645 ToUsingDir->setLexicalDeclContext(LexicalDC);
4646 LexicalDC->addDeclInternal(ToUsingDir);
4647
4648 return ToUsingDir;
4649}
4650
4651ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingValueDecl(
4652 UnresolvedUsingValueDecl *D) {
4653 DeclContext *DC, *LexicalDC;
4654 DeclarationName Name;
4655 SourceLocation Loc;
4656 NamedDecl *ToD = nullptr;
4657 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4658 return std::move(Err);
4659 if (ToD)
4660 return ToD;
4661
4662 Error Err = Error::success();
4663 auto ToLoc = importChecked(Err, D->getNameInfo().getLoc());
4664 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4665 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4666 auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc());
4667 if (Err)
4668 return std::move(Err);
4669
4670 DeclarationNameInfo NameInfo(Name, ToLoc);
4671 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
4672 return std::move(Err);
4673
4674 UnresolvedUsingValueDecl *ToUsingValue;
4675 if (GetImportedOrCreateDecl(ToUsingValue, D, Importer.getToContext(), DC,
4676 ToUsingLoc, ToQualifierLoc, NameInfo,
4677 ToEllipsisLoc))
4678 return ToUsingValue;
4679
4680 ToUsingValue->setAccess(D->getAccess());
4681 ToUsingValue->setLexicalDeclContext(LexicalDC);
4682 LexicalDC->addDeclInternal(ToUsingValue);
4683
4684 return ToUsingValue;
4685}
4686
4687ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingTypenameDecl(
4688 UnresolvedUsingTypenameDecl *D) {
4689 DeclContext *DC, *LexicalDC;
4690 DeclarationName Name;
4691 SourceLocation Loc;
4692 NamedDecl *ToD = nullptr;
4693 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4694 return std::move(Err);
4695 if (ToD)
4696 return ToD;
4697
4698 Error Err = Error::success();
4699 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4700 auto ToTypenameLoc = importChecked(Err, D->getTypenameLoc());
4701 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4702 auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc());
4703 if (Err)
4704 return std::move(Err);
4705
4706 UnresolvedUsingTypenameDecl *ToUsing;
4707 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
4708 ToUsingLoc, ToTypenameLoc,
4709 ToQualifierLoc, Loc, Name, ToEllipsisLoc))
4710 return ToUsing;
4711
4712 ToUsing->setAccess(D->getAccess());
4713 ToUsing->setLexicalDeclContext(LexicalDC);
4714 LexicalDC->addDeclInternal(ToUsing);
4715
4716 return ToUsing;
4717}
4718
4719ExpectedDecl ASTNodeImporter::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
4720 Decl* ToD = nullptr;
4721 switch (D->getBuiltinTemplateKind()) {
4722 case BuiltinTemplateKind::BTK__make_integer_seq:
4723 ToD = Importer.getToContext().getMakeIntegerSeqDecl();
4724 break;
4725 case BuiltinTemplateKind::BTK__type_pack_element:
4726 ToD = Importer.getToContext().getTypePackElementDecl();
4727 break;
4728 }
4729 assert(ToD && "BuiltinTemplateDecl of unsupported kind!")((ToD && "BuiltinTemplateDecl of unsupported kind!") ?
static_cast<void> (0) : __assert_fail ("ToD && \"BuiltinTemplateDecl of unsupported kind!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 4729, __PRETTY_FUNCTION__))
;
4730 Importer.MapImported(D, ToD);
4731 return ToD;
4732}
4733
4734Error ASTNodeImporter::ImportDefinition(
4735 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, ImportDefinitionKind Kind) {
4736 if (To->getDefinition()) {
4737 // Check consistency of superclass.
4738 ObjCInterfaceDecl *FromSuper = From->getSuperClass();
4739 if (FromSuper) {
4740 if (auto FromSuperOrErr = import(FromSuper))
4741 FromSuper = *FromSuperOrErr;
4742 else
4743 return FromSuperOrErr.takeError();
4744 }
4745
4746 ObjCInterfaceDecl *ToSuper = To->getSuperClass();
4747 if ((bool)FromSuper != (bool)ToSuper ||
4748 (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
4749 Importer.ToDiag(To->getLocation(),
4750 diag::warn_odr_objc_superclass_inconsistent)
4751 << To->getDeclName();
4752 if (ToSuper)
4753 Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
4754 << To->getSuperClass()->getDeclName();
4755 else
4756 Importer.ToDiag(To->getLocation(),
4757 diag::note_odr_objc_missing_superclass);
4758 if (From->getSuperClass())
4759 Importer.FromDiag(From->getSuperClassLoc(),
4760 diag::note_odr_objc_superclass)
4761 << From->getSuperClass()->getDeclName();
4762 else
4763 Importer.FromDiag(From->getLocation(),
4764 diag::note_odr_objc_missing_superclass);
4765 }
4766
4767 if (shouldForceImportDeclContext(Kind))
4768 if (Error Err = ImportDeclContext(From))
4769 return Err;
4770 return Error::success();
4771 }
4772
4773 // Start the definition.
4774 To->startDefinition();
4775
4776 // If this class has a superclass, import it.
4777 if (From->getSuperClass()) {
4778 if (auto SuperTInfoOrErr = import(From->getSuperClassTInfo()))
4779 To->setSuperClass(*SuperTInfoOrErr);
4780 else
4781 return SuperTInfoOrErr.takeError();
4782 }
4783
4784 // Import protocols
4785 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4786 SmallVector<SourceLocation, 4> ProtocolLocs;
4787 ObjCInterfaceDecl::protocol_loc_iterator FromProtoLoc =
4788 From->protocol_loc_begin();
4789
4790 for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
4791 FromProtoEnd = From->protocol_end();
4792 FromProto != FromProtoEnd;
4793 ++FromProto, ++FromProtoLoc) {
4794 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4795 Protocols.push_back(*ToProtoOrErr);
4796 else
4797 return ToProtoOrErr.takeError();
4798
4799 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4800 ProtocolLocs.push_back(*ToProtoLocOrErr);
4801 else
4802 return ToProtoLocOrErr.takeError();
4803
4804 }
4805
4806 // FIXME: If we're merging, make sure that the protocol list is the same.
4807 To->setProtocolList(Protocols.data(), Protocols.size(),
4808 ProtocolLocs.data(), Importer.getToContext());
4809
4810 // Import categories. When the categories themselves are imported, they'll
4811 // hook themselves into this interface.
4812 for (auto *Cat : From->known_categories()) {
4813 auto ToCatOrErr = import(Cat);
4814 if (!ToCatOrErr)
4815 return ToCatOrErr.takeError();
4816 }
4817
4818 // If we have an @implementation, import it as well.
4819 if (From->getImplementation()) {
4820 if (Expected<ObjCImplementationDecl *> ToImplOrErr =
4821 import(From->getImplementation()))
4822 To->setImplementation(*ToImplOrErr);
4823 else
4824 return ToImplOrErr.takeError();
4825 }
4826
4827 // Import all of the members of this class.
4828 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4829 return Err;
4830
4831 return Error::success();
4832}
4833
4834Expected<ObjCTypeParamList *>
4835ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) {
4836 if (!list)
4837 return nullptr;
4838
4839 SmallVector<ObjCTypeParamDecl *, 4> toTypeParams;
4840 for (auto *fromTypeParam : *list) {
4841 if (auto toTypeParamOrErr = import(fromTypeParam))
4842 toTypeParams.push_back(*toTypeParamOrErr);
4843 else
4844 return toTypeParamOrErr.takeError();
4845 }
4846
4847 auto LAngleLocOrErr = import(list->getLAngleLoc());
4848 if (!LAngleLocOrErr)
4849 return LAngleLocOrErr.takeError();
4850
4851 auto RAngleLocOrErr = import(list->getRAngleLoc());
4852 if (!RAngleLocOrErr)
4853 return RAngleLocOrErr.takeError();
4854
4855 return ObjCTypeParamList::create(Importer.getToContext(),
4856 *LAngleLocOrErr,
4857 toTypeParams,
4858 *RAngleLocOrErr);
4859}
4860
4861ExpectedDecl ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
4862 // If this class has a definition in the translation unit we're coming from,
4863 // but this particular declaration is not that definition, import the
4864 // definition and map to that.
4865 ObjCInterfaceDecl *Definition = D->getDefinition();
4866 if (Definition && Definition != D) {
4867 if (ExpectedDecl ImportedDefOrErr = import(Definition))
4868 return Importer.MapImported(D, *ImportedDefOrErr);
4869 else
4870 return ImportedDefOrErr.takeError();
4871 }
4872
4873 // Import the major distinguishing characteristics of an @interface.
4874 DeclContext *DC, *LexicalDC;
4875 DeclarationName Name;
4876 SourceLocation Loc;
4877 NamedDecl *ToD;
4878 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4879 return std::move(Err);
4880 if (ToD)
4881 return ToD;
4882
4883 // Look for an existing interface with the same name.
4884 ObjCInterfaceDecl *MergeWithIface = nullptr;
4885 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4886 for (auto *FoundDecl : FoundDecls) {
4887 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4888 continue;
4889
4890 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl)))
4891 break;
4892 }
4893
4894 // Create an interface declaration, if one does not already exist.
4895 ObjCInterfaceDecl *ToIface = MergeWithIface;
4896 if (!ToIface) {
4897 ExpectedSLoc AtBeginLocOrErr = import(D->getAtStartLoc());
4898 if (!AtBeginLocOrErr)
4899 return AtBeginLocOrErr.takeError();
4900
4901 if (GetImportedOrCreateDecl(
4902 ToIface, D, Importer.getToContext(), DC,
4903 *AtBeginLocOrErr, Name.getAsIdentifierInfo(),
4904 /*TypeParamList=*/nullptr,
4905 /*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl()))
4906 return ToIface;
4907 ToIface->setLexicalDeclContext(LexicalDC);
4908 LexicalDC->addDeclInternal(ToIface);
4909 }
4910 Importer.MapImported(D, ToIface);
4911 // Import the type parameter list after MapImported, to avoid
4912 // loops when bringing in their DeclContext.
4913 if (auto ToPListOrErr =
4914 ImportObjCTypeParamList(D->getTypeParamListAsWritten()))
4915 ToIface->setTypeParamList(*ToPListOrErr);
4916 else
4917 return ToPListOrErr.takeError();
4918
4919 if (D->isThisDeclarationADefinition())
4920 if (Error Err = ImportDefinition(D, ToIface))
4921 return std::move(Err);
4922
4923 return ToIface;
4924}
4925
4926ExpectedDecl
4927ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
4928 ObjCCategoryDecl *Category;
4929 if (Error Err = importInto(Category, D->getCategoryDecl()))
4930 return std::move(Err);
4931
4932 ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
4933 if (!ToImpl) {
4934 DeclContext *DC, *LexicalDC;
4935 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4936 return std::move(Err);
4937
4938 Error Err = Error::success();
4939 auto ToLocation = importChecked(Err, D->getLocation());
4940 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
4941 auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc());
4942 if (Err)
4943 return std::move(Err);
4944
4945 if (GetImportedOrCreateDecl(
4946 ToImpl, D, Importer.getToContext(), DC,
4947 Importer.Import(D->getIdentifier()), Category->getClassInterface(),
4948 ToLocation, ToAtStartLoc, ToCategoryNameLoc))
4949 return ToImpl;
4950
4951 ToImpl->setLexicalDeclContext(LexicalDC);
4952 LexicalDC->addDeclInternal(ToImpl);
4953 Category->setImplementation(ToImpl);
4954 }
4955
4956 Importer.MapImported(D, ToImpl);
4957 if (Error Err = ImportDeclContext(D))
4958 return std::move(Err);
4959
4960 return ToImpl;
4961}
4962
4963ExpectedDecl
4964ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
4965 // Find the corresponding interface.
4966 ObjCInterfaceDecl *Iface;
4967 if (Error Err = importInto(Iface, D->getClassInterface()))
4968 return std::move(Err);
4969
4970 // Import the superclass, if any.
4971 ObjCInterfaceDecl *Super;
4972 if (Error Err = importInto(Super, D->getSuperClass()))
4973 return std::move(Err);
4974
4975 ObjCImplementationDecl *Impl = Iface->getImplementation();
4976 if (!Impl) {
4977 // We haven't imported an implementation yet. Create a new @implementation
4978 // now.
4979 DeclContext *DC, *LexicalDC;
4980 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4981 return std::move(Err);
4982
4983 Error Err = Error::success();
4984 auto ToLocation = importChecked(Err, D->getLocation());
4985 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
4986 auto ToSuperClassLoc = importChecked(Err, D->getSuperClassLoc());
4987 auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc());
4988 auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc());
4989 if (Err)
4990 return std::move(Err);
4991
4992 if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(),
4993 DC, Iface, Super,
4994 ToLocation,
4995 ToAtStartLoc,
4996 ToSuperClassLoc,
4997 ToIvarLBraceLoc,
4998 ToIvarRBraceLoc))
4999 return Impl;
5000
5001 Impl->setLexicalDeclContext(LexicalDC);
5002
5003 // Associate the implementation with the class it implements.
5004 Iface->setImplementation(Impl);
5005 Importer.MapImported(D, Iface->getImplementation());
5006 } else {
5007 Importer.MapImported(D, Iface->getImplementation());
5008
5009 // Verify that the existing @implementation has the same superclass.
5010 if ((Super && !Impl->getSuperClass()) ||
5011 (!Super && Impl->getSuperClass()) ||
5012 (Super && Impl->getSuperClass() &&
5013 !declaresSameEntity(Super->getCanonicalDecl(),
5014 Impl->getSuperClass()))) {
5015 Importer.ToDiag(Impl->getLocation(),
5016 diag::warn_odr_objc_superclass_inconsistent)
5017 << Iface->getDeclName();
5018 // FIXME: It would be nice to have the location of the superclass
5019 // below.
5020 if (Impl->getSuperClass())
5021 Importer.ToDiag(Impl->getLocation(),
5022 diag::note_odr_objc_superclass)
5023 << Impl->getSuperClass()->getDeclName();
5024 else
5025 Importer.ToDiag(Impl->getLocation(),
5026 diag::note_odr_objc_missing_superclass);
5027 if (D->getSuperClass())
5028 Importer.FromDiag(D->getLocation(),
5029 diag::note_odr_objc_superclass)
5030 << D->getSuperClass()->getDeclName();
5031 else
5032 Importer.FromDiag(D->getLocation(),
5033 diag::note_odr_objc_missing_superclass);
5034
5035 return make_error<ImportError>(ImportError::NameConflict);
5036 }
5037 }
5038
5039 // Import all of the members of this @implementation.
5040 if (Error Err = ImportDeclContext(D))
5041 return std::move(Err);
5042
5043 return Impl;
5044}
5045
5046ExpectedDecl ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
5047 // Import the major distinguishing characteristics of an @property.
5048 DeclContext *DC, *LexicalDC;
5049 DeclarationName Name;
5050 SourceLocation Loc;
5051 NamedDecl *ToD;
5052 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5053 return std::move(Err);
5054 if (ToD)
5055 return ToD;
5056
5057 // Check whether we have already imported this property.
5058 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5059 for (auto *FoundDecl : FoundDecls) {
5060 if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(FoundDecl)) {
5061 // Check property types.
5062 if (!Importer.IsStructurallyEquivalent(D->getType(),
5063 FoundProp->getType())) {
5064 Importer.ToDiag(Loc, diag::warn_odr_objc_property_type_inconsistent)
5065 << Name << D->getType() << FoundProp->getType();
5066 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
5067 << FoundProp->getType();
5068
5069 return make_error<ImportError>(ImportError::NameConflict);
5070 }
5071
5072 // FIXME: Check property attributes, getters, setters, etc.?
5073
5074 // Consider these properties to be equivalent.
5075 Importer.MapImported(D, FoundProp);
5076 return FoundProp;
5077 }
5078 }
5079
5080 Error Err = Error::success();
5081 auto ToType = importChecked(Err, D->getType());
5082 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
5083 auto ToAtLoc = importChecked(Err, D->getAtLoc());
5084 auto ToLParenLoc = importChecked(Err, D->getLParenLoc());
5085 if (Err)
5086 return std::move(Err);
5087
5088 // Create the new property.
5089 ObjCPropertyDecl *ToProperty;
5090 if (GetImportedOrCreateDecl(
5091 ToProperty, D, Importer.getToContext(), DC, Loc,
5092 Name.getAsIdentifierInfo(), ToAtLoc,
5093 ToLParenLoc, ToType,
5094 ToTypeSourceInfo, D->getPropertyImplementation()))
5095 return ToProperty;
5096
5097 auto ToGetterName = importChecked(Err, D->getGetterName());
5098 auto ToSetterName = importChecked(Err, D->getSetterName());
5099 auto ToGetterNameLoc = importChecked(Err, D->getGetterNameLoc());
5100 auto ToSetterNameLoc = importChecked(Err, D->getSetterNameLoc());
5101 auto ToGetterMethodDecl = importChecked(Err, D->getGetterMethodDecl());
5102 auto ToSetterMethodDecl = importChecked(Err, D->getSetterMethodDecl());
5103 auto ToPropertyIvarDecl = importChecked(Err, D->getPropertyIvarDecl());
5104 if (Err)
5105 return std::move(Err);
5106
5107 ToProperty->setLexicalDeclContext(LexicalDC);
5108 LexicalDC->addDeclInternal(ToProperty);
5109
5110 ToProperty->setPropertyAttributes(D->getPropertyAttributes());
5111 ToProperty->setPropertyAttributesAsWritten(
5112 D->getPropertyAttributesAsWritten());
5113 ToProperty->setGetterName(ToGetterName, ToGetterNameLoc);
5114 ToProperty->setSetterName(ToSetterName, ToSetterNameLoc);
5115 ToProperty->setGetterMethodDecl(ToGetterMethodDecl);
5116 ToProperty->setSetterMethodDecl(ToSetterMethodDecl);
5117 ToProperty->setPropertyIvarDecl(ToPropertyIvarDecl);
5118 return ToProperty;
5119}
5120
5121ExpectedDecl
5122ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
5123 ObjCPropertyDecl *Property;
5124 if (Error Err = importInto(Property, D->getPropertyDecl()))
5125 return std::move(Err);
5126
5127 DeclContext *DC, *LexicalDC;
5128 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5129 return std::move(Err);
5130
5131 auto *InImpl = cast<ObjCImplDecl>(LexicalDC);
5132
5133 // Import the ivar (for an @synthesize).
5134 ObjCIvarDecl *Ivar = nullptr;
5135 if (Error Err = importInto(Ivar, D->getPropertyIvarDecl()))
5136 return std::move(Err);
5137
5138 ObjCPropertyImplDecl *ToImpl
5139 = InImpl->FindPropertyImplDecl(Property->getIdentifier(),
5140 Property->getQueryKind());
5141 if (!ToImpl) {
5142
5143 Error Err = Error::success();
5144 auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
5145 auto ToLocation = importChecked(Err, D->getLocation());
5146 auto ToPropertyIvarDeclLoc =
5147 importChecked(Err, D->getPropertyIvarDeclLoc());
5148 if (Err)
5149 return std::move(Err);
5150
5151 if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC,
5152 ToBeginLoc,
5153 ToLocation, Property,
5154 D->getPropertyImplementation(), Ivar,
5155 ToPropertyIvarDeclLoc))
5156 return ToImpl;
5157
5158 ToImpl->setLexicalDeclContext(LexicalDC);
5159 LexicalDC->addDeclInternal(ToImpl);
5160 } else {
5161 // Check that we have the same kind of property implementation (@synthesize
5162 // vs. @dynamic).
5163 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
5164 Importer.ToDiag(ToImpl->getLocation(),
5165 diag::warn_odr_objc_property_impl_kind_inconsistent)
5166 << Property->getDeclName()
5167 << (ToImpl->getPropertyImplementation()
5168 == ObjCPropertyImplDecl::Dynamic);
5169 Importer.FromDiag(D->getLocation(),
5170 diag::note_odr_objc_property_impl_kind)
5171 << D->getPropertyDecl()->getDeclName()
5172 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
5173
5174 return make_error<ImportError>(ImportError::NameConflict);
5175 }
5176
5177 // For @synthesize, check that we have the same
5178 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
5179 Ivar != ToImpl->getPropertyIvarDecl()) {
5180 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
5181 diag::warn_odr_objc_synthesize_ivar_inconsistent)
5182 << Property->getDeclName()
5183 << ToImpl->getPropertyIvarDecl()->getDeclName()
5184 << Ivar->getDeclName();
5185 Importer.FromDiag(D->getPropertyIvarDeclLoc(),
5186 diag::note_odr_objc_synthesize_ivar_here)
5187 << D->getPropertyIvarDecl()->getDeclName();
5188
5189 return make_error<ImportError>(ImportError::NameConflict);
5190 }
5191
5192 // Merge the existing implementation with the new implementation.
5193 Importer.MapImported(D, ToImpl);
5194 }
5195
5196 return ToImpl;
5197}
5198
5199ExpectedDecl
5200ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
5201 // For template arguments, we adopt the translation unit as our declaration
5202 // context. This context will be fixed when the actual template declaration
5203 // is created.
5204
5205 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5206 if (!BeginLocOrErr)
5207 return BeginLocOrErr.takeError();
5208
5209 ExpectedSLoc LocationOrErr = import(D->getLocation());
5210 if (!LocationOrErr)
5211 return LocationOrErr.takeError();
5212
5213 TemplateTypeParmDecl *ToD = nullptr;
5214 if (GetImportedOrCreateDecl(
5215 ToD, D, Importer.getToContext(),
5216 Importer.getToContext().getTranslationUnitDecl(),
5217 *BeginLocOrErr, *LocationOrErr,
5218 D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()),
5219 D->wasDeclaredWithTypename(), D->isParameterPack(),
5220 D->hasTypeConstraint()))
5221 return ToD;
5222
5223 // Import the type-constraint
5224 if (const TypeConstraint *TC = D->getTypeConstraint()) {
5225
5226 Error Err = Error::success();
5227 auto ToNNS = importChecked(Err, TC->getNestedNameSpecifierLoc());
5228 auto ToName = importChecked(Err, TC->getConceptNameInfo().getName());
5229 auto ToNameLoc = importChecked(Err, TC->getConceptNameInfo().getLoc());
5230 auto ToFoundDecl = importChecked(Err, TC->getFoundDecl());
5231 auto ToNamedConcept = importChecked(Err, TC->getNamedConcept());
5232 auto ToIDC = importChecked(Err, TC->getImmediatelyDeclaredConstraint());
5233 if (Err)
5234 return std::move(Err);
5235
5236 TemplateArgumentListInfo ToTAInfo;
5237 const auto *ASTTemplateArgs = TC->getTemplateArgsAsWritten();
5238 if (ASTTemplateArgs)
5239 if (Error Err = ImportTemplateArgumentListInfo(*ASTTemplateArgs,
5240 ToTAInfo))
5241 return std::move(Err);
5242
5243 ToD->setTypeConstraint(ToNNS, DeclarationNameInfo(ToName, ToNameLoc),
5244 ToFoundDecl, ToNamedConcept,
5245 ASTTemplateArgs ?
5246 ASTTemplateArgumentListInfo::Create(Importer.getToContext(),
5247 ToTAInfo) : nullptr,
5248 ToIDC);
5249 }
5250
5251 if (D->hasDefaultArgument()) {
5252 Expected<TypeSourceInfo *> ToDefaultArgOrErr =
5253 import(D->getDefaultArgumentInfo());
5254 if (!ToDefaultArgOrErr)
5255 return ToDefaultArgOrErr.takeError();
5256 ToD->setDefaultArgument(*ToDefaultArgOrErr);
5257 }
5258
5259 return ToD;
5260}
5261
5262ExpectedDecl
5263ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
5264
5265 Error Err = Error::success();
5266 auto ToDeclName = importChecked(Err, D->getDeclName());
5267 auto ToLocation = importChecked(Err, D->getLocation());
5268 auto ToType = importChecked(Err, D->getType());
5269 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
5270 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
5271 if (Err)
5272 return std::move(Err);
5273
5274 NonTypeTemplateParmDecl *ToD = nullptr;
5275 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(),
5276 Importer.getToContext().getTranslationUnitDecl(),
5277 ToInnerLocStart, ToLocation, D->getDepth(),
5278 D->getPosition(),
5279 ToDeclName.getAsIdentifierInfo(), ToType,
5280 D->isParameterPack(), ToTypeSourceInfo))
5281 return ToD;
5282
5283 if (D->hasDefaultArgument()) {
5284 ExpectedExpr ToDefaultArgOrErr = import(D->getDefaultArgument());
5285 if (!ToDefaultArgOrErr)
5286 return ToDefaultArgOrErr.takeError();
5287 ToD->setDefaultArgument(*ToDefaultArgOrErr);
5288 }
5289
5290 return ToD;
5291}
5292
5293ExpectedDecl
5294ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
5295 // Import the name of this declaration.
5296 auto NameOrErr = import(D->getDeclName());
5297 if (!NameOrErr)
5298 return NameOrErr.takeError();
5299
5300 // Import the location of this declaration.
5301 ExpectedSLoc LocationOrErr = import(D->getLocation());
5302 if (!LocationOrErr)
5303 return LocationOrErr.takeError();
5304
5305 // Import template parameters.
5306 auto TemplateParamsOrErr = import(D->getTemplateParameters());
5307 if (!TemplateParamsOrErr)
5308 return TemplateParamsOrErr.takeError();
5309
5310 TemplateTemplateParmDecl *ToD = nullptr;
5311 if (GetImportedOrCreateDecl(
5312 ToD, D, Importer.getToContext(),
5313 Importer.getToContext().getTranslationUnitDecl(), *LocationOrErr,
5314 D->getDepth(), D->getPosition(), D->isParameterPack(),
5315 (*NameOrErr).getAsIdentifierInfo(), *TemplateParamsOrErr))
5316 return ToD;
5317
5318 if (D->hasDefaultArgument()) {
5319 Expected<TemplateArgumentLoc> ToDefaultArgOrErr =
5320 import(D->getDefaultArgument());
5321 if (!ToDefaultArgOrErr)
5322 return ToDefaultArgOrErr.takeError();
5323 ToD->setDefaultArgument(Importer.getToContext(), *ToDefaultArgOrErr);
5324 }
5325
5326 return ToD;
5327}
5328
5329// Returns the definition for a (forward) declaration of a TemplateDecl, if
5330// it has any definition in the redecl chain.
5331template <typename T> static auto getTemplateDefinition(T *D) -> T * {
5332 assert(D->getTemplatedDecl() && "Should be called on templates only")((D->getTemplatedDecl() && "Should be called on templates only"
) ? static_cast<void> (0) : __assert_fail ("D->getTemplatedDecl() && \"Should be called on templates only\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 5332, __PRETTY_FUNCTION__))
;
5333 auto *ToTemplatedDef = D->getTemplatedDecl()->getDefinition();
5334 if (!ToTemplatedDef)
5335 return nullptr;
5336 auto *TemplateWithDef = ToTemplatedDef->getDescribedTemplate();
5337 return cast_or_null<T>(TemplateWithDef);
5338}
5339
5340ExpectedDecl ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
5341
5342 // Import the major distinguishing characteristics of this class template.
5343 DeclContext *DC, *LexicalDC;
5344 DeclarationName Name;
5345 SourceLocation Loc;
5346 NamedDecl *ToD;
5347 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5348 return std::move(Err);
5349 if (ToD)
5350 return ToD;
5351
5352 ClassTemplateDecl *FoundByLookup = nullptr;
5353
5354 // We may already have a template of the same name; try to find and match it.
5355 if (!DC->isFunctionOrMethod()) {
5356 SmallVector<NamedDecl *, 4> ConflictingDecls;
5357 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5358 for (auto *FoundDecl : FoundDecls) {
5359 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary |
5360 Decl::IDNS_TagFriend))
5361 continue;
5362
5363 Decl *Found = FoundDecl;
5364 auto *FoundTemplate = dyn_cast<ClassTemplateDecl>(Found);
5365 if (FoundTemplate) {
5366 if (!hasSameVisibilityContextAndLinkage(FoundTemplate, D))
5367 continue;
5368
5369 if (IsStructuralMatch(D, FoundTemplate)) {
5370 ClassTemplateDecl *TemplateWithDef =
5371 getTemplateDefinition(FoundTemplate);
5372 if (D->isThisDeclarationADefinition() && TemplateWithDef)
5373 return Importer.MapImported(D, TemplateWithDef);
5374 if (!FoundByLookup)
5375 FoundByLookup = FoundTemplate;
5376 // Search in all matches because there may be multiple decl chains,
5377 // see ASTTests test ImportExistingFriendClassTemplateDef.
5378 continue;
5379 }
5380 ConflictingDecls.push_back(FoundDecl);
5381 }
5382 }
5383
5384 if (!ConflictingDecls.empty()) {
5385 ExpectedName NameOrErr = Importer.HandleNameConflict(
5386 Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(),
5387 ConflictingDecls.size());
5388 if (NameOrErr)
5389 Name = NameOrErr.get();
5390 else
5391 return NameOrErr.takeError();
5392 }
5393 }
5394
5395 CXXRecordDecl *FromTemplated = D->getTemplatedDecl();
5396
5397 auto TemplateParamsOrErr = import(D->getTemplateParameters());
5398 if (!TemplateParamsOrErr)
5399 return TemplateParamsOrErr.takeError();
5400
5401 // Create the declaration that is being templated.
5402 CXXRecordDecl *ToTemplated;
5403 if (Error Err = importInto(ToTemplated, FromTemplated))
5404 return std::move(Err);
5405
5406 // Create the class template declaration itself.
5407 ClassTemplateDecl *D2;
5408 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, Loc, Name,
5409 *TemplateParamsOrErr, ToTemplated))
5410 return D2;
5411
5412 ToTemplated->setDescribedClassTemplate(D2);
5413
5414 D2->setAccess(D->getAccess());
5415 D2->setLexicalDeclContext(LexicalDC);
5416
5417 addDeclToContexts(D, D2);
5418
5419 if (FoundByLookup) {
5420 auto *Recent =
5421 const_cast<ClassTemplateDecl *>(FoundByLookup->getMostRecentDecl());
5422
5423 // It is possible that during the import of the class template definition
5424 // we start the import of a fwd friend decl of the very same class template
5425 // and we add the fwd friend decl to the lookup table. But the ToTemplated
5426 // had been created earlier and by that time the lookup could not find
5427 // anything existing, so it has no previous decl. Later, (still during the
5428 // import of the fwd friend decl) we start to import the definition again
5429 // and this time the lookup finds the previous fwd friend class template.
5430 // In this case we must set up the previous decl for the templated decl.
5431 if (!ToTemplated->getPreviousDecl()) {
5432 assert(FoundByLookup->getTemplatedDecl() &&((FoundByLookup->getTemplatedDecl() && "Found decl must have its templated decl set"
) ? static_cast<void> (0) : __assert_fail ("FoundByLookup->getTemplatedDecl() && \"Found decl must have its templated decl set\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 5433, __PRETTY_FUNCTION__))
5433 "Found decl must have its templated decl set")((FoundByLookup->getTemplatedDecl() && "Found decl must have its templated decl set"
) ? static_cast<void> (0) : __assert_fail ("FoundByLookup->getTemplatedDecl() && \"Found decl must have its templated decl set\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 5433, __PRETTY_FUNCTION__))
;
5434 CXXRecordDecl *PrevTemplated =
5435 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
5436 if (ToTemplated != PrevTemplated)
5437 ToTemplated->setPreviousDecl(PrevTemplated);
5438 }
5439
5440 D2->setPreviousDecl(Recent);
5441 }
5442
5443 if (FromTemplated->isCompleteDefinition() &&
5444 !ToTemplated->isCompleteDefinition()) {
5445 // FIXME: Import definition!
5446 }
5447
5448 return D2;
5449}
5450
5451ExpectedDecl ASTNodeImporter::VisitClassTemplateSpecializationDecl(
5452 ClassTemplateSpecializationDecl *D) {
5453 ClassTemplateDecl *ClassTemplate;
5454 if (Error Err = importInto(ClassTemplate, D->getSpecializedTemplate()))
5455 return std::move(Err);
5456
5457 // Import the context of this declaration.
5458 DeclContext *DC, *LexicalDC;
5459 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5460 return std::move(Err);
5461
5462 // Import template arguments.
5463 SmallVector<TemplateArgument, 2> TemplateArgs;
5464 if (Error Err = ImportTemplateArguments(
5465 D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs))
5466 return std::move(Err);
5467 // Try to find an existing specialization with these template arguments and
5468 // template parameter list.
5469 void *InsertPos = nullptr;
5470 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
5471 ClassTemplatePartialSpecializationDecl *PartialSpec =
5472 dyn_cast<ClassTemplatePartialSpecializationDecl>(D);
5473
5474 // Import template parameters.
5475 TemplateParameterList *ToTPList = nullptr;
5476
5477 if (PartialSpec) {
5478 auto ToTPListOrErr = import(PartialSpec->getTemplateParameters());
5479 if (!ToTPListOrErr)
5480 return ToTPListOrErr.takeError();
5481 ToTPList = *ToTPListOrErr;
5482 PrevDecl = ClassTemplate->findPartialSpecialization(TemplateArgs,
5483 *ToTPListOrErr,
5484 InsertPos);
5485 } else
5486 PrevDecl = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
5487
5488 if (PrevDecl) {
5489 if (IsStructuralMatch(D, PrevDecl)) {
5490 CXXRecordDecl *PrevDefinition = PrevDecl->getDefinition();
5491 if (D->isThisDeclarationADefinition() && PrevDefinition) {
5492 Importer.MapImported(D, PrevDefinition);
5493 // Import those default field initializers which have been
5494 // instantiated in the "From" context, but not in the "To" context.
5495 for (auto *FromField : D->fields()) {
5496 auto ToOrErr = import(FromField);
5497 if (!ToOrErr)
5498 return ToOrErr.takeError();
5499 }
5500
5501 // Import those methods which have been instantiated in the
5502 // "From" context, but not in the "To" context.
5503 for (CXXMethodDecl *FromM : D->methods()) {
5504 auto ToOrErr = import(FromM);
5505 if (!ToOrErr)
5506 return ToOrErr.takeError();
5507 }
5508
5509 // TODO Import instantiated default arguments.
5510 // TODO Import instantiated exception specifications.
5511 //
5512 // Generally, ASTCommon.h/DeclUpdateKind enum gives a very good hint
5513 // what else could be fused during an AST merge.
5514 return PrevDefinition;
5515 }
5516 } else { // ODR violation.
5517 // FIXME HandleNameConflict
5518 return make_error<ImportError>(ImportError::NameConflict);
5519 }
5520 }
5521
5522 // Import the location of this declaration.
5523 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5524 if (!BeginLocOrErr)
5525 return BeginLocOrErr.takeError();
5526 ExpectedSLoc IdLocOrErr = import(D->getLocation());
5527 if (!IdLocOrErr)
5528 return IdLocOrErr.takeError();
5529
5530 // Create the specialization.
5531 ClassTemplateSpecializationDecl *D2 = nullptr;
5532 if (PartialSpec) {
5533 // Import TemplateArgumentListInfo.
5534 TemplateArgumentListInfo ToTAInfo;
5535 const auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten();
5536 if (Error Err = ImportTemplateArgumentListInfo(ASTTemplateArgs, ToTAInfo))
5537 return std::move(Err);
5538
5539 QualType CanonInjType;
5540 if (Error Err = importInto(
5541 CanonInjType, PartialSpec->getInjectedSpecializationType()))
5542 return std::move(Err);
5543 CanonInjType = CanonInjType.getCanonicalType();
5544
5545 if (GetImportedOrCreateDecl<ClassTemplatePartialSpecializationDecl>(
5546 D2, D, Importer.getToContext(), D->getTagKind(), DC,
5547 *BeginLocOrErr, *IdLocOrErr, ToTPList, ClassTemplate,
5548 llvm::makeArrayRef(TemplateArgs.data(), TemplateArgs.size()),
5549 ToTAInfo, CanonInjType,
5550 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl)))
5551 return D2;
5552
5553 // Update InsertPos, because preceding import calls may have invalidated
5554 // it by adding new specializations.
5555 auto *PartSpec2 = cast<ClassTemplatePartialSpecializationDecl>(D2);
5556 if (!ClassTemplate->findPartialSpecialization(TemplateArgs, ToTPList,
5557 InsertPos))
5558 // Add this partial specialization to the class template.
5559 ClassTemplate->AddPartialSpecialization(PartSpec2, InsertPos);
5560
5561 } else { // Not a partial specialization.
5562 if (GetImportedOrCreateDecl(
5563 D2, D, Importer.getToContext(), D->getTagKind(), DC,
5564 *BeginLocOrErr, *IdLocOrErr, ClassTemplate, TemplateArgs,
5565 PrevDecl))
5566 return D2;
5567
5568 // Update InsertPos, because preceding import calls may have invalidated
5569 // it by adding new specializations.
5570 if (!ClassTemplate->findSpecialization(TemplateArgs, InsertPos))
5571 // Add this specialization to the class template.
5572 ClassTemplate->AddSpecialization(D2, InsertPos);
5573 }
5574
5575 D2->setSpecializationKind(D->getSpecializationKind());
5576
5577 // Set the context of this specialization/instantiation.
5578 D2->setLexicalDeclContext(LexicalDC);
5579
5580 // Add to the DC only if it was an explicit specialization/instantiation.
5581 if (D2->isExplicitInstantiationOrSpecialization()) {
5582 LexicalDC->addDeclInternal(D2);
5583 }
5584
5585 if (auto BraceRangeOrErr = import(D->getBraceRange()))
5586 D2->setBraceRange(*BraceRangeOrErr);
5587 else
5588 return BraceRangeOrErr.takeError();
5589
5590 // Import the qualifier, if any.
5591 if (auto LocOrErr = import(D->getQualifierLoc()))
5592 D2->setQualifierInfo(*LocOrErr);
5593 else
5594 return LocOrErr.takeError();
5595
5596 if (auto *TSI = D->getTypeAsWritten()) {
5597 if (auto TInfoOrErr = import(TSI))
5598 D2->setTypeAsWritten(*TInfoOrErr);
5599 else
5600 return TInfoOrErr.takeError();
5601
5602 if (auto LocOrErr = import(D->getTemplateKeywordLoc()))
5603 D2->setTemplateKeywordLoc(*LocOrErr);
5604 else
5605 return LocOrErr.takeError();
5606
5607 if (auto LocOrErr = import(D->getExternLoc()))
5608 D2->setExternLoc(*LocOrErr);
5609 else
5610 return LocOrErr.takeError();
5611 }
5612
5613 if (D->getPointOfInstantiation().isValid()) {
5614 if (auto POIOrErr = import(D->getPointOfInstantiation()))
5615 D2->setPointOfInstantiation(*POIOrErr);
5616 else
5617 return POIOrErr.takeError();
5618 }
5619
5620 D2->setTemplateSpecializationKind(D->getTemplateSpecializationKind());
5621
5622 if (D->isCompleteDefinition())
5623 if (Error Err = ImportDefinition(D, D2))
5624 return std::move(Err);
5625
5626 return D2;
5627}
5628
5629ExpectedDecl ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
5630 // Import the major distinguishing characteristics of this variable template.
5631 DeclContext *DC, *LexicalDC;
5632 DeclarationName Name;
5633 SourceLocation Loc;
5634 NamedDecl *ToD;
5635 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5636 return std::move(Err);
5637 if (ToD)
5638 return ToD;
5639
5640 // We may already have a template of the same name; try to find and match it.
5641 assert(!DC->isFunctionOrMethod() &&((!DC->isFunctionOrMethod() && "Variable templates cannot be declared at function scope"
) ? static_cast<void> (0) : __assert_fail ("!DC->isFunctionOrMethod() && \"Variable templates cannot be declared at function scope\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 5642, __PRETTY_FUNCTION__))
5642 "Variable templates cannot be declared at function scope")((!DC->isFunctionOrMethod() && "Variable templates cannot be declared at function scope"
) ? static_cast<void> (0) : __assert_fail ("!DC->isFunctionOrMethod() && \"Variable templates cannot be declared at function scope\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 5642, __PRETTY_FUNCTION__))
;
5643
5644 SmallVector<NamedDecl *, 4> ConflictingDecls;
5645 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5646 VarTemplateDecl *FoundByLookup = nullptr;
5647 for (auto *FoundDecl : FoundDecls) {
5648 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5649 continue;
5650
5651 if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(FoundDecl)) {
5652 // Use the templated decl, some linkage flags are set only there.
5653 if (!hasSameVisibilityContextAndLinkage(FoundTemplate->getTemplatedDecl(),
5654 D->getTemplatedDecl()))
5655 continue;
5656 if (IsStructuralMatch(D, FoundTemplate)) {
5657 // The Decl in the "From" context has a definition, but in the
5658 // "To" context we already have a definition.
5659 VarTemplateDecl *FoundDef = getTemplateDefinition(FoundTemplate);
5660 if (D->isThisDeclarationADefinition() && FoundDef)
5661 // FIXME Check for ODR error if the two definitions have
5662 // different initializers?
5663 return Importer.MapImported(D, FoundDef);
5664
5665 FoundByLookup = FoundTemplate;
5666 break;
5667 }
5668 ConflictingDecls.push_back(FoundDecl);
5669 }
5670 }
5671
5672 if (!ConflictingDecls.empty()) {
5673 ExpectedName NameOrErr = Importer.HandleNameConflict(
5674 Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(),
5675 ConflictingDecls.size());
5676 if (NameOrErr)
5677 Name = NameOrErr.get();
5678 else
5679 return NameOrErr.takeError();
5680 }
5681
5682 VarDecl *DTemplated = D->getTemplatedDecl();
5683
5684 // Import the type.
5685 // FIXME: Value not used?
5686 ExpectedType TypeOrErr = import(DTemplated->getType());
5687 if (!TypeOrErr)
5688 return TypeOrErr.takeError();
5689
5690 // Create the declaration that is being templated.
5691 VarDecl *ToTemplated;
5692 if (Error Err = importInto(ToTemplated, DTemplated))
5693 return std::move(Err);
5694
5695 // Create the variable template declaration itself.
5696 auto TemplateParamsOrErr = import(D->getTemplateParameters());
5697 if (!TemplateParamsOrErr)
5698 return TemplateParamsOrErr.takeError();
5699
5700 VarTemplateDecl *ToVarTD;
5701 if (GetImportedOrCreateDecl(ToVarTD, D, Importer.getToContext(), DC, Loc,
5702 Name, *TemplateParamsOrErr, ToTemplated))
5703 return ToVarTD;
5704
5705 ToTemplated->setDescribedVarTemplate(ToVarTD);
5706
5707 ToVarTD->setAccess(D->getAccess());
5708 ToVarTD->setLexicalDeclContext(LexicalDC);
5709 LexicalDC->addDeclInternal(ToVarTD);
5710
5711 if (FoundByLookup) {
5712 auto *Recent =
5713 const_cast<VarTemplateDecl *>(FoundByLookup->getMostRecentDecl());
5714 if (!ToTemplated->getPreviousDecl()) {
5715 auto *PrevTemplated =
5716 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
5717 if (ToTemplated != PrevTemplated)
5718 ToTemplated->setPreviousDecl(PrevTemplated);
5719 }
5720 ToVarTD->setPreviousDecl(Recent);
5721 }
5722
5723 if (DTemplated->isThisDeclarationADefinition() &&
5724 !ToTemplated->isThisDeclarationADefinition()) {
5725 // FIXME: Import definition!
5726 }
5727
5728 return ToVarTD;
5729}
5730
5731ExpectedDecl ASTNodeImporter::VisitVarTemplateSpecializationDecl(
5732 VarTemplateSpecializationDecl *D) {
5733 // If this record has a definition in the translation unit we're coming from,
5734 // but this particular declaration is not that definition, import the
5735 // definition and map to that.
5736 VarDecl *Definition = D->getDefinition();
5737 if (Definition && Definition != D) {
5738 if (ExpectedDecl ImportedDefOrErr = import(Definition))
5739 return Importer.MapImported(D, *ImportedDefOrErr);
5740 else
5741 return ImportedDefOrErr.takeError();
5742 }
5743
5744 VarTemplateDecl *VarTemplate = nullptr;
5745 if (Error Err = importInto(VarTemplate, D->getSpecializedTemplate()))
5746 return std::move(Err);
5747
5748 // Import the context of this declaration.
5749 DeclContext *DC, *LexicalDC;
5750 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5751 return std::move(Err);
5752
5753 // Import the location of this declaration.
5754 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5755 if (!BeginLocOrErr)
5756 return BeginLocOrErr.takeError();
5757
5758 auto IdLocOrErr = import(D->getLocation());
5759 if (!IdLocOrErr)
5760 return IdLocOrErr.takeError();
5761
5762 // Import template arguments.
5763 SmallVector<TemplateArgument, 2> TemplateArgs;
5764 if (Error Err = ImportTemplateArguments(
5765 D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs))
5766 return std::move(Err);
5767
5768 // Try to find an existing specialization with these template arguments.
5769 void *InsertPos = nullptr;
5770 VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
5771 TemplateArgs, InsertPos);
5772 if (D2) {
5773 // We already have a variable template specialization with these template
5774 // arguments.
5775
5776 // FIXME: Check for specialization vs. instantiation errors.
5777
5778 if (VarDecl *FoundDef = D2->getDefinition()) {
5779 if (!D->isThisDeclarationADefinition() ||
5780 IsStructuralMatch(D, FoundDef)) {
5781 // The record types structurally match, or the "from" translation
5782 // unit only had a forward declaration anyway; call it the same
5783 // variable.
5784 return Importer.MapImported(D, FoundDef);
5785 }
5786 }
5787 } else {
5788 // Import the type.
5789 QualType T;
5790 if (Error Err = importInto(T, D->getType()))
5791 return std::move(Err);
5792
5793 auto TInfoOrErr = import(D->getTypeSourceInfo());
5794 if (!TInfoOrErr)
5795 return TInfoOrErr.takeError();
5796
5797 TemplateArgumentListInfo ToTAInfo;
5798 if (Error Err = ImportTemplateArgumentListInfo(
5799 D->getTemplateArgsInfo(), ToTAInfo))
5800 return std::move(Err);
5801
5802 using PartVarSpecDecl = VarTemplatePartialSpecializationDecl;
5803 // Create a new specialization.
5804 if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(D)) {
5805 // Import TemplateArgumentListInfo
5806 TemplateArgumentListInfo ArgInfos;
5807 const auto *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten();
5808 // NOTE: FromTAArgsAsWritten and template parameter list are non-null.
5809 if (Error Err = ImportTemplateArgumentListInfo(
5810 *FromTAArgsAsWritten, ArgInfos))
5811 return std::move(Err);
5812
5813 auto ToTPListOrErr = import(FromPartial->getTemplateParameters());
5814 if (!ToTPListOrErr)
5815 return ToTPListOrErr.takeError();
5816
5817 PartVarSpecDecl *ToPartial;
5818 if (GetImportedOrCreateDecl(ToPartial, D, Importer.getToContext(), DC,
5819 *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr,
5820 VarTemplate, T, *TInfoOrErr,
5821 D->getStorageClass(), TemplateArgs, ArgInfos))
5822 return ToPartial;
5823
5824 if (Expected<PartVarSpecDecl *> ToInstOrErr = import(
5825 FromPartial->getInstantiatedFromMember()))
5826 ToPartial->setInstantiatedFromMember(*ToInstOrErr);
5827 else
5828 return ToInstOrErr.takeError();
5829
5830 if (FromPartial->isMemberSpecialization())
5831 ToPartial->setMemberSpecialization();
5832
5833 D2 = ToPartial;
5834
5835 } else { // Full specialization
5836 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC,
5837 *BeginLocOrErr, *IdLocOrErr, VarTemplate,
5838 T, *TInfoOrErr,
5839 D->getStorageClass(), TemplateArgs))
5840 return D2;
5841 }
5842
5843 if (D->getPointOfInstantiation().isValid()) {
5844 if (ExpectedSLoc POIOrErr = import(D->getPointOfInstantiation()))
5845 D2->setPointOfInstantiation(*POIOrErr);
5846 else
5847 return POIOrErr.takeError();
5848 }
5849
5850 D2->setSpecializationKind(D->getSpecializationKind());
5851 D2->setTemplateArgsInfo(ToTAInfo);
5852
5853 // Add this specialization to the class template.
5854 VarTemplate->AddSpecialization(D2, InsertPos);
5855
5856 // Import the qualifier, if any.
5857 if (auto LocOrErr = import(D->getQualifierLoc()))
5858 D2->setQualifierInfo(*LocOrErr);
5859 else
5860 return LocOrErr.takeError();
5861
5862 if (D->isConstexpr())
5863 D2->setConstexpr(true);
5864
5865 // Add the specialization to this context.
5866 D2->setLexicalDeclContext(LexicalDC);
5867 LexicalDC->addDeclInternal(D2);
5868
5869 D2->setAccess(D->getAccess());
5870 }
5871
5872 if (Error Err = ImportInitializer(D, D2))
5873 return std::move(Err);
5874
5875 return D2;
5876}
5877
5878ExpectedDecl
5879ASTNodeImporter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
5880 DeclContext *DC, *LexicalDC;
5881 DeclarationName Name;
5882 SourceLocation Loc;
5883 NamedDecl *ToD;
5884
5885 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5886 return std::move(Err);
5887
5888 if (ToD)
5889 return ToD;
5890
5891 const FunctionTemplateDecl *FoundByLookup = nullptr;
5892
5893 // Try to find a function in our own ("to") context with the same name, same
5894 // type, and in the same context as the function we're importing.
5895 // FIXME Split this into a separate function.
5896 if (!LexicalDC->isFunctionOrMethod()) {
5897 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
5898 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5899 for (auto *FoundDecl : FoundDecls) {
5900 if (!FoundDecl->isInIdentifierNamespace(IDNS))
5901 continue;
5902
5903 if (auto *FoundTemplate = dyn_cast<FunctionTemplateDecl>(FoundDecl)) {
5904 if (!hasSameVisibilityContextAndLinkage(FoundTemplate, D))
5905 continue;
5906 if (IsStructuralMatch(D, FoundTemplate)) {
5907 FunctionTemplateDecl *TemplateWithDef =
5908 getTemplateDefinition(FoundTemplate);
5909 if (D->isThisDeclarationADefinition() && TemplateWithDef)
5910 return Importer.MapImported(D, TemplateWithDef);
5911
5912 FoundByLookup = FoundTemplate;
5913 break;
5914 // TODO: handle conflicting names
5915 }
5916 }
5917 }
5918 }
5919
5920 auto ParamsOrErr = import(D->getTemplateParameters());
5921 if (!ParamsOrErr)
5922 return ParamsOrErr.takeError();
5923
5924 FunctionDecl *TemplatedFD;
5925 if (Error Err = importInto(TemplatedFD, D->getTemplatedDecl()))
5926 return std::move(Err);
5927
5928 FunctionTemplateDecl *ToFunc;
5929 if (GetImportedOrCreateDecl(ToFunc, D, Importer.getToContext(), DC, Loc, Name,
5930 *ParamsOrErr, TemplatedFD))
5931 return ToFunc;
5932
5933 TemplatedFD->setDescribedFunctionTemplate(ToFunc);
5934
5935 ToFunc->setAccess(D->getAccess());
5936 ToFunc->setLexicalDeclContext(LexicalDC);
5937 LexicalDC->addDeclInternal(ToFunc);
5938
5939 if (FoundByLookup) {
5940 auto *Recent =
5941 const_cast<FunctionTemplateDecl *>(FoundByLookup->getMostRecentDecl());
5942 if (!TemplatedFD->getPreviousDecl()) {
5943 assert(FoundByLookup->getTemplatedDecl() &&((FoundByLookup->getTemplatedDecl() && "Found decl must have its templated decl set"
) ? static_cast<void> (0) : __assert_fail ("FoundByLookup->getTemplatedDecl() && \"Found decl must have its templated decl set\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 5944, __PRETTY_FUNCTION__))
5944 "Found decl must have its templated decl set")((FoundByLookup->getTemplatedDecl() && "Found decl must have its templated decl set"
) ? static_cast<void> (0) : __assert_fail ("FoundByLookup->getTemplatedDecl() && \"Found decl must have its templated decl set\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/AST/ASTImporter.cpp"
, 5944, __PRETTY_FUNCTION__))
;
5945 auto *PrevTemplated =
5946 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
5947 if (TemplatedFD != PrevTemplated)
5948 TemplatedFD->setPreviousDecl(PrevTemplated);
5949 }
5950 ToFunc->setPreviousDecl(Recent);
5951 }
5952
5953 return ToFunc;
5954}
5955
5956//----------------------------------------------------------------------------
5957// Import Statements
5958//----------------------------------------------------------------------------
5959
5960ExpectedStmt ASTNodeImporter::VisitStmt(Stmt *S) {
5961 Importer.FromDiag(S->getBeginLoc(), diag::err_unsupported_ast_node)
5962 << S->getStmtClassName();
5963 return make_error<ImportError>(ImportError::UnsupportedConstruct);
5964}
5965
5966
5967ExpectedStmt ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) {
5968 if (Importer.returnWithErrorInTest())
5969 return make_error<ImportError>(ImportError::UnsupportedConstruct);
5970 SmallVector<IdentifierInfo *, 4> Names;
5971 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
5972 IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I));
5973 // ToII is nullptr when no symbolic name is given for output operand
5974 // see ParseStmtAsm::ParseAsmOperandsOpt
5975 Names.push_back(ToII);
5976 }
5977
5978 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
5979 IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I));
5980 // ToII is nullptr when no symbolic name is given for input operand
5981 // see ParseStmtAsm::ParseAsmOperandsOpt
5982 Names.push_back(ToII);
5983 }
5984
5985 SmallVector<StringLiteral *, 4> Clobbers;
5986 for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) {
5987 if (auto ClobberOrErr = import(S->getClobberStringLiteral(I)))
5988 Clobbers.push_back(*ClobberOrErr);
5989 else
5990 return ClobberOrErr.takeError();
5991
5992 }
5993
5994 SmallVector<StringLiteral *, 4> Constraints;
5995 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
5996 if (auto OutputOrErr = import(S->getOutputConstraintLiteral(I)))
5997 Constraints.push_back(*OutputOrErr);
5998 else
5999 return OutputOrErr.takeError();
6000 }
6001
6002 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
6003 if (auto InputOrErr = import(S->getInputConstraintLiteral(I)))
6004 Constraints.push_back(*InputOrErr);
6005 else
6006 return InputOrErr.takeError();
6007 }
6008
6009 SmallVector<Expr *, 4> Exprs(S->getNumOutputs() + S->getNumInputs() +
6010 S->getNumLabels());
6011 if (Error Err = ImportContainerChecked(S->outputs(), Exprs))
6012 return std::move(Err);
6013
6014 if (Error Err =
6015 ImportArrayChecked(S->inputs(), Exprs.begin() + S->getNumOutputs()))
6016 return std::move(Err);
6017
6018 if (Error Err = ImportArrayChecked(
6019 S->labels(), Exprs.begin() + S->getNumOutputs() + S->getNumInputs()))
6020 return std::move(Err);
6021
6022 ExpectedSLoc AsmLocOrErr = import(S->getAsmLoc());
6023 if (!AsmLocOrErr)
6024 return AsmLocOrErr.takeError();
6025 auto AsmStrOrErr = import(S->getAsmString());
6026 if (!AsmStrOrErr)
6027 return AsmStrOrErr.takeError();
6028 ExpectedSLoc RParenLocOrErr = import(S->getRParenLoc());
6029 if (!RParenLocOrErr)
6030 return RParenLocOrErr.takeError();
6031
6032 return new (Importer.getToContext()) GCCAsmStmt(
6033 Importer.getToContext(),
6034 *AsmLocOrErr,
6035 S->isSimple(),
6036 S->isVolatile(),
6037 S->getNumOutputs(),
6038 S->getNumInputs(),
6039 Names.data(),
6040 Constraints.data(),
6041 Exprs.data(),
6042 *AsmStrOrErr,
6043 S->getNumClobbers(),
6044 Clobbers.data(),
6045 S->getNumLabels(),
6046 *RParenLocOrErr);
6047}
6048
6049ExpectedStmt ASTNodeImporter::VisitDeclStmt(DeclStmt *S) {
6050
6051 Error Err = Error::success();
6052 auto ToDG = importChecked(Err, S->getDeclGroup());
6053 auto ToBeginLoc = importChecked(Err, S->getBeginLoc());
6054 auto ToEndLoc = importChecked(Err, S->getEndLoc());
6055 if (Err)
6056 return std::move(Err);
6057 return new (Importer.getToContext()) DeclStmt(ToDG, ToBeginLoc, ToEndLoc);
6058}
6059
6060ExpectedStmt ASTNodeImporter::VisitNullStmt(NullStmt *S) {
6061 ExpectedSLoc ToSemiLocOrErr = import(S->getSemiLoc());
6062 if (!ToSemiLocOrErr)
6063 return ToSemiLocOrErr.takeError();
6064 return new (Importer.getToContext()) NullStmt(
6065 *ToSemiLocOrErr, S->hasLeadingEmptyMacro());
6066}
6067
6068ExpectedStmt ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) {
6069 SmallVector<Stmt *, 8> ToStmts(S->size());
6070
6071 if (Error Err = ImportContainerChecked(S->body(), ToStmts))
6072 return std::move(Err);
6073
6074 ExpectedSLoc ToLBracLocOrErr = import(S->getLBracLoc());
6075 if (!ToLBracLocOrErr)
6076 return ToLBracLocOrErr.takeError();
6077
6078 ExpectedSLoc ToRBracLocOrErr = import(S->getRBracLoc());
6079 if (!ToRBracLocOrErr)
6080 return ToRBracLocOrErr.takeError();
6081
6082 return CompoundStmt::Create(
6083 Importer.getToContext(), ToStmts,
6084 *ToLBracLocOrErr, *ToRBracLocOrErr);
6085}
6086
6087ExpectedStmt ASTNodeImporter::V