Bug Summary

File:clang/lib/AST/ASTImporter.cpp
Warning:line 3342, 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 _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20201130111130+b5fbc60e4de/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20201130111130+b5fbc60e4de/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20201130111130+b5fbc60e4de/clang/include -I /build/llvm-toolchain-snapshot-12~++20201130111130+b5fbc60e4de/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20201130111130+b5fbc60e4de/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20201130111130+b5fbc60e4de/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~++20201130111130+b5fbc60e4de/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20201130111130+b5fbc60e4de=. -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-11-30-155233-8884-1 -x c++ /build/llvm-toolchain-snapshot-12~++20201130111130+b5fbc60e4de/clang/lib/AST/ASTImporter.cpp

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