Bug Summary

File:src/gnu/usr.bin/clang/libclangAST/../../../llvm/clang/lib/AST/ASTImporter.cpp
Warning:line 5125, column 34
Called C++ object pointer is uninitialized

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -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 -mrelocation-model static -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangAST/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/libclangAST/obj/../include/clang/AST -I /usr/src/gnu/usr.bin/clang/libclangAST/../../../llvm/clang/include -I /usr/src/gnu/usr.bin/clang/libclangAST/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/libclangAST/../include -I /usr/src/gnu/usr.bin/clang/libclangAST/obj -I /usr/src/gnu/usr.bin/clang/libclangAST/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangAST/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -stack-protector 2 -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/libclangAST/../../../llvm/clang/lib/AST/ASTImporter.cpp

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