Bug Summary

File:clang/lib/AST/ASTImporter.cpp
Warning:line 3376, 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 -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 CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/include -I /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/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~++20201026111116+d3205bbca3e/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e=. -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-2020-10-27-053609-25509-1 -x c++ /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/ASTImporter.cpp

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